很抱歉,如果这是一个noob问题,但我目前正在学习C ++。我有一个函数,它接受几个参数 - 我想在创建3D int数组时使用这些参数。
void* testFunction(int countX, int countY, int countZ)
{
const int NX = countX;
const int NY = countY;
const int NZ = countZ;
int* data_out = new int*[NX][NY][NZ];
// The above line throws the error on "NY" - expression must
// have a constant value
}
我从各种帖子中了解到你必须首先分配阵列但我想我做错了吗?如何正确初始化多维数组。另外,为什么初始化需要指针?
答案 0 :(得分:2)
解释错误:C ++在其new
运算符中需要一个类型的名称。类型名称不能具有运行时维度,因为C ++中的所有类型都是静态的(在编译时确定)。
例如,这会分配3个int[4][5]
类型的元素:
new int[3][4][5];
另一个例子:这会分配类型为int[4][5]
的NX元素:
new int[NX][4][5];
一个不正确的例子:如果C ++支持"动态"这将分配类型int[NY][NZ]
的NX元素。类型:
new int[NX][NY][NZ];
要分配三维数组或类似的数组,您可以使用std::vector
:
std::vector<std::vector<std::vector<int>>> my_3D_array;
... // initialization goes here
my_3D_array[2][2][2] = 222; // whatever you want to do with it
为了使语法更简洁,并简化初始化,请使用typedef
(或此处using
,这是相同的):
using int_1D = std::vector<int>; // this is a 1-dimensional array type
using int_2D = std::vector<int_1D>; // this is a 2-dimensional array type
using int_3D = std::vector<int_2D>; // this is a 3-dimensional array type
int_3D data(NX, int_2D(NY, int_1D(NZ))); // allocate a 3-D array, elements initialized to 0
data[2][2][2] = 222;
如果要从函数中返回此数组,则应声明它;你不能只返回一个void
指向data
变量的指针。以下是声明的语法:
using int_1D = std::vector<int>;
using int_2D = std::vector<int_1D>;
using int_3D = std::vector<int_2D>;
int_3D testFunction(int countX, int countY, int countZ)
{
int_3D data(...);
...
return data;
}
也就是说,不要使用new
,而只需使用std::vector<whatever>
,就好像它是任何其他类型一样。