正确的方法来声明一个可变长度的二维数组在C ++中 [英] Proper way to declare a variable length two dimensional array in C++
问题描述
我想获得一个二维int数组改编
,我可以通过访问改编[I] [J]。
I would like to get a two dimensional int array arr
that I can access via arr[i][j].
据我了解,我可以声明 INT改编[10] [15];
来得到这样一个数组。
在我的情况下,大小不过是可变的,据我了解,如果数组的大小并不难codeD,但我使用像 INT ARR一个变量[SIZEX此语法不起作用] [SIZEY]
。
As far as I understand I could declare int arr[10][15];
to get such an array.
In my case the size is however variable and as far as I understand this syntax doesn't work if the size of the array isn't hardcoded but I use a variable like int arr[sizeX][sizeY]
.
什么是最好的解决办法?
What's the best workaround?
推荐答案
如果你不希望使用的 的std ::矢量
载体(或新的C ++ 11的 的std ::阵列
),那么你必须手动分配所有子阵:
If you don't want to use a std::vector
of vectors (or the new C++11 std::array
) then you have to allocate all sub-arrays manually:
int **arr = new int* [sizeX];
for (int i = 0; i < sizeX; i++)
arr[i] = new int[sizeY];
当然,不要忘了删除[]
全部完成时。
这篇关于正确的方法来声明一个可变长度的二维数组在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!