动态数组 C++

发布于 2025-01-02 14:09:00 字数 234 浏览 1 评论 0原文

我想在 for 循环中动态创建数组。我有如下内容:

for (int i = 0; i < line; i++){

complex* in[i] = new complex[8];

}

复杂是用户定义的数据类型。有什么办法可以实现上述操作吗?我为此收到错误。我想为多个数组创建几个指针(无法说出我需要多少个数组),其中每个指针都指向一个特定的数组。

提前致谢。

I want to create arrays dynamically within the for loop. I have something like bellow:

for (int i = 0; i < line; i++){

complex* in[i] = new complex[8];

}

complex is a user defined data type. Is there any way to do the above operation. I am getting error for that. I want to create few pointers for more than one array (can't say how many arrays I will need) where each pointer will point to a particular array.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黎歌 2025-01-09 14:09:00

如果您的“内部”数组都是 8 个元素,则可以使用此方法来动态调整大小的 complex 数组(包含 8 个元素):

std::vector<std::array<complex, 8> > c(line);
// new and delete are not needed here

您当然可以替换 std::vector在这种情况下,std::array 的 code> -- std::array 可能不可用,具体取决于您使用的库。

当元素计数不变时,std::arraystd::vector 更精确。因此,std::array 可以进行大量 std::vector 无法进行的优化。这对您的计划的影响可能是可衡量的,也可能是不可衡量的。

这样做的好处是,库的实现经过了良好的测试,可以使您免受并检测一些使用错误。

If your 'inner' arrays are all 8 elements each, you can use this approach for a dynamically resizable array of complex arrays of 8 elements:

std::vector<std::array<complex, 8> > c(line);
// new and delete are not needed here

You could of course substitute std::vector for std::array in this case -- std::array may not be available depending on the library you're using.

std::array is a little more exact than std::vector when the element count is invariant. Thus, std::array can make a ton of optimizations std::vector cannot. How that affects your program may or may not be measurable.

The good thing about this is that the library implementations are well tested, will insulate you from and detect some usage errors.

东京女 2025-01-09 14:09:00

构造complex *in[i] = ... 没有意义。您不能逐个声明数组的元素。您必须在循环之前声明整个数组。

即,如下所示

complex *in[MAX_LINES];
// or you can allocate in[] dynamically:
// complex *in[] = new (complex*)[line];

for (int i = 0; i < line; i++){
    in[i] = new complex[8];
}

当然,除非您特别需要 C 样式数组(例如 - 用于与 C 代码交互),否则最好使用 C++ 向量/数组(如 Justin 在另一个答案中所示)。

The construct complex *in[i] = ... does not make sense. You cannot declare the elements of an array one after the other. You have to declare the entire array before the loop.

I.e., something like the following

complex *in[MAX_LINES];
// or you can allocate in[] dynamically:
// complex *in[] = new (complex*)[line];

for (int i = 0; i < line; i++){
    in[i] = new complex[8];
}

Of course, unless you specifically need C-style arrays (for example - for interfacing with C code), it is probably better to use C++ vectors/arrays (as Justin had shown in another answer).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文