简体   繁体   English

多维数组的常数

[英]Constant for a multi-dimensional array

I'm trying to create a multi-dimensional array, the size of which the user will supply. 我正在尝试创建一个多维数组,用户将提供其大小。

So far I have this: 到目前为止,我有这个:

int definedgroups; // for number of groups needed

cout << "Enter the Number of Groups you require: " << endl;
cin >> definedgroups;
const int definedgroups = definedgroups;

int User_Groups [definedgroups] [4];

I believe the array needs constant values, so i tried assigning my variable as a constant but still no luck. 我相信数组需要常量值,因此我尝试将变量分配为常量,但仍然没有运气。

In C++, static arrays, that is, those defined like this: 在C ++中, 静态数组(即,定义如下):

foo arrayStatic[bar];

require bar to be a constant integer. 要求bar为常数整数。 In other words, the programmer needs to know its value beforehand. 换句话说,程序员需要事先知道其值。

Whenever bar is unknown, a dynamic array could be used instead. 每当bar未知时,都可以使用动态数组代替。 They're defined like this: 它们的定义如下:

foo* arrayDynamic;
arrayDynamic = new foo[bar];

Here, bar could be an integer variable. 在这里, bar可以是整数变量。

Don't forget that dynamic memory must be deallocated eventually. 不要忘记动态内存必须最终释放。 So, in this case, we can deallocate arrayDynamic like this: 因此,在这种情况下,我们可以像这样取消分配arrayDynamic

delete [] arrayDynamic; 

A two-dimensional dynamic array is defined analogously: 二维动态数组的定义类似:

foo** arrayDynamic2D;
arrayDynamic2D = new foo*[bar];
for (int i = 0; i < bar; i++)
   arrayDynamic2D[i] = new foo[baz];

and deallocated in a similar fashion: 并以类似的方式释放:

for (int i = 0; i < bar; i++)
   delete [] arrayDynamic2D[i];
delete [] arrayDynamic2D;

Static memory is allocated in the stack whereas dynamic memory is allocated in the heap . 静态内存在堆栈中分配,而动态内存在堆中分配。

It's not possible to do it in C++ using static arrays. 使用静态数组在C ++中是不可能做到的。 Use std::vector in a hierarchical way (ie vectors of vectors) to implement a multi-dimensional array easily (though not necessarily very efficiently). 以分层方式使用std::vector (即向量的向量)来轻松实现多维数组(尽管不一定非常有效)。

Eg 例如

std::vector<std::vector<double> > array(nrows, std::vector<double>(ncols));

creates a nrows x ncols matrix. 创建一个nrows x ncols矩阵。

You need dynamic memory allocation using new : 您需要使用new动态分配内存:

int **User_Groups = new int*[definedgroups];
//Allocate memory for 2nd dimension
for (int i = 0; i < 4; ++i)
    User_Groups[i] = new int[4];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM