如何使程序声明可变数量的不定大小数组

时间:2013-10-06 15:55:16

标签: c++ c arrays loops variable-length-array

这可能听起来很疯狂,但我想知道是否可以使用C / C ++在循环中使程序声明narray[]类型的数组。例如,对此伪代码进行采样:

input int _n_  

run loop for _n_ times such that:  
declare _array1[]_  
declare _array2[]_  
.  
.  
declare _array'n'[]_ 

所以这里的问题有两方面:
- 声明可变长度数组
- 声明一个变量号(即 n 号)这样的数组。

2 个答案:

答案 0 :(得分:4)

真相表:

task        / language         | C                   | C++
-------------------------------+-----------------------+------------------------
Declare variable length arrays | Use VLAs            | not possible without
                               |      int arr[n];    | non-standard extensions
                               |                     | but use std::vector<T>
-------------------------------+---------------------+--------------------------
Declare a variable number      |  not possible but   | not possible but use
(i.e. n number of) such arrays |  use int arr[n][k]; | vector<vector<T>> 

答案 1 :(得分:2)

我理解它的方式,如果你想要多个阵列,你不能只使用2D阵列吗?这当然意味着您没有数组的可变长度,但是您可以拥有可变数量的具有相同长度的数组。

然后你有这个:

int n;
int array[n][length];