【问题标题】:Instantiating a 3D array in C++ using parameters使用参数在 C++ 中实例化 3D 数组
【发布时间】:2017-01-05 03:42:49
【问题描述】:

对不起,如果这是一个菜鸟问题,但我目前正在学习 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
}

从各种帖子中我了解到您必须先分配数组,但我想我做错了?如何正确初始化多维数组。还有,为什么初始化需要指针?

【问题讨论】:

  • 理想情况下,您应该使用一维 vectorunique_ptr<T[]> 并使用数学伪造三个维度。
  • @MichaelO。您的建议仍然会引发相同的“表达式必须具有恒定值”错误。编辑:“const int NZ - countZ”是一种类型 - 我编辑了帖子以获得正确的“=”。
  • 简答:你不能这样做。长答案:你不应该这样做。数组是错误的工具,因为它们不跟踪自己的大小。请参阅 NathanOliver 的评论。
  • @NathanOliver 你们有谁知道我在哪里可以找到一个简单的例子来说明这个概念吗?

标签: c++ arrays


【解决方案1】:

解释错误:C++ 在其new 运算符中需要一个类型的名称。类型的名称不能有运行时维度,因为 C++ 中的所有类型都是静态的(在编译时确定)。

例如,这分配了int[4][5]类型的3个元素:

new int[3][4][5];

另一个例子:这分配了int[4][5]类型的NX元素:

new int[NX][4][5];

一个不正确的例子:如果 C++ 支持“动态”类型,这将分配类型为 int[NY][NZ] 的 NX 元素:

new int[NX][NY][NZ];

要分配一个 3 维数组,或者类似的东西,你可以使用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&lt;whatever&gt;,就好像它是任何其他类型一样。

【讨论】:

    猜你喜欢
    • 2019-09-02
    • 2017-05-19
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多