简体   繁体   English

在C ++中通过引用传递3维可变大小数组

[英]Passing a 3-dimensional variable size array by reference in C++

I've been working off of Passing a 2D array to a C++ function , as well as a few other similar articles. 我一直在研究将2D数组传递给C ++函数 ,以及其他一些类似的文章。 However, I'm running into a problem wherein the array I'm creating has two dimensions of variable size. 但是,我遇到了一个问题,其中我正在创建的数组具有两个尺寸可变的维。

The initialization looks like: 初始化看起来像:

int** mulePosition;
mulePosition = new int *[boardSize][boardSize][2];

The function looks like: 该函数如下所示:

int moveMule (int boardSize, int ***mulePosition)

And the references look like 和引用看起来像

moveMule (boardSize, mulePosition)

Boardsize is defined at the beginning of the function, but may change per execution. Boardsize是在函数的开头定义的,但每次执行可能会更改。 The array, properly sized, would be int [boardSize][boardSize][2]. 适当大小的数组应为int [boardSize] [boardSize] [2]。

Either use a plain '3-dimensional' array via 通过以下方式使用普通的“ 3维”数组

int* mulePosition = new int[boardsize*boardsize*2];

and address its elements calculating the offset from the beginning: mulePosition[a][b][c] is mulePosition[boardSize*2*a + 2*b + c] , 并从开始计算地址以计算偏移量:mulePosition [a] [b] [c]是mulePosition[boardSize*2*a + 2*b + c]

or use array of arrays of arrays (which would correspond to your int*** declaration) or better (and simpler) vector of vectors of vectors, although the initialization would be a little more complex (you would need to initialize every array/vector). 或使用arrays的arrays数组(这将对应于您的int***声明)或vectors的vectors的更好(或更简单)的vectors,尽管初始化会稍微复杂一些(您将需要初始化每个array / vector )。

Either use a std::vector<std::vector<int>> if boardSize is not a const or std::array<std::array<boardSize>, boardSize> (see Multidimensional std::array for how to initialize the std::array). 既可以使用一个std::vector<std::vector<int>>如果boardSize不是const或std::array<std::array<boardSize>, boardSize>参见多维的std ::阵列为如何初始化std :: array)。

That being said, it looks like a good idea to hide this in a class Board which provides a nice interface. 话虽如此,将其隐藏在提供良好界面的类Board中似乎是一个好主意。

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

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