动态数组 C++
我想在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的“内部”数组都是 8 个元素,则可以使用此方法来动态调整大小的
complex
数组(包含 8 个元素):您当然可以替换
std::vector
在这种情况下,std::array
的 code> --std::array
可能不可用,具体取决于您使用的库。当元素计数不变时,
std::array
比std::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:You could of course substitute
std::vector
forstd::array
in this case --std::array
may not be available depending on the library you're using.std::array
is a little more exact thanstd::vector
when the element count is invariant. Thus,std::array
can make a ton of optimizationsstd::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.
构造
complex *in[i] = ...
没有意义。您不能逐个声明数组的元素。您必须在循环之前声明整个数组。即,如下所示
当然,除非您特别需要 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
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).