我一直在尝试创建一个可变长度的多维数组。据我了解,您不能在堆栈上创建可变长度数组,但可以使用动态分配在 C++ 中创建一维可变长度数组。如果这是一个编译器扩展,请纠正我,但它似乎在设置 --pedantic 的 clang 和 gcc 上运行良好。
int size = 10;
int *ary = new int[size]();
我试图将这个概念扩展到多维数组。这是我的结果。可能性 1 和 2 的问题在于它们需要一个 constexpr 并且不适用于可变大小。是否可以让它们中的任何一个接受一个变量作为它的大小?据我所知,我提出了可能性 3,但它缺少 [][] 访问权限,这正是我正在寻找的。p>
constexpr int constSize = 10;
//Possibility 1: Only works in C++11
//Creates CONTIGUOUS 2D array equivalent to array[n*n], but with [][] access
int (*ary1)[constSize] = new int[constSize][constSize]();
delete [] ary1;
//Possibility 2:
//Really horrible as it does NOT create a contiguous 2D array
//Instead creates n seperate arrays that are each themselves contiguous
//Also requires a lot of deletes, quite messy
int **ary2 = new int*[constSize];
for (int i = 0; i < n; ++i)
ary2[i] = new int[constSize];
for (int i = 0; i < n; ++i)
delete [] ary2;
delete [] ary2;
//Possibility 3:
//This DOES work with non-constexpr variable
//However it does not offer [][] access, need to access element using ary[i*n+j]
int *ary3 = new int[size*size];
delete [] ary3;
最佳答案
这将创建一个动态分配的二维可变长度数组,维度为 w
和 h
:
std::vector<std::vector<int>> ary4(w, std::vector<int>(h));
可以通过[][]
访问:
ary4[x][y] = 0;
但是,它不是连续分配的。要获得一个连续的数组,这里有一个解决方案:
template<typename E>
class Contiguous2DArray
{
public:
Contiguous2DArray(std::size_t width, std::size_t height)
: array(width * height), width(width) {}
E& operator()(std::size_t x, std::size_t y)
{ return array[x + width * y]; }
private:
std::vector<E> array;
std::size_t width;
}
可以这样使用:
Contiguous2DArray<int> ary5(w, h);
ary5(x, y) = 0;
关于C++11 动态分配可变长度多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993265/