3

假设我有一个多维数组,在 C99 中我可以这样写:

#define SIZE1 10
int size2;

[...]

int myArray[SIZE1][size2];

尽管有多个编译器支持,但这并不是严格意义上的 C++,直到 C++14 才会包含在内。为了使用 boost::scoped_array 获得相同的(除了堆栈/堆问题与我的情况无关),我写道:

boost::scoped_array<int> myArray[SIZE1];
for (int i = 0; i < SIZE1; i++)
    myArray[i].reset(new int[size2]);

所以,不是那么简洁的表达方式。我是否遗漏了什么,或者对于具有可变长度的多维数组,没有简单的普通 C++ 方法来获得快速分配?

一些参考:为什么可变长度数组不是 C++ 标准的一部分?

4

4 回答 4

2

std::vector将采用大小和初始值,您可以使用它来设置外部和内部向量的初始大小:

vector< vector<int> > myArray(SIZE1, vector<int>(size2));

boost::multi_array专门设计为多维数组,比boost::scoped_array.

boost::multi_array<int, 2> myArray(boost::extents[SIZE1][size2])
于 2014-02-07T12:57:22.100 回答
0

C++ 标准中没有可变长度的多维数组,但您可以轻松编写自己的矩阵类,其中包含一个向量,通过“row_index*rowlength + column_index”计算向量索引。

于 2014-02-07T12:52:26.420 回答
0

没有默认容器,如果你只想要一个分配,你需要写一个。这是我能给出的最短的例子:

template <class T>
class Matrix
{
public:
    Matrix(const unsigned int _width,const unsigned int _height)
        :width(_width)
        ,height(_height)
    {
        elements.resize(width * height);//one allocation !
    }
    //x goes on width
    //y on height
    T&              get(const unsigned int x,const unsigned int y)
    {
        return elements[y * width + x];
    }
public:
    unsigned int    width;
    unsigned int    height;
    std::vector<T>  elements;
};

//usage:
Matrix<int> m(width_size,height_size);
m.get(10,10) = element;

请注意,所有元素都分配在一个向量中,并在xyi 处找到一个元素,用于y * width + x获取向量中的索引。

也已经有为此目的的实现,所以最好从互联网上获取一个。您可以查看boost 库中的内容。

于 2014-02-07T12:53:34.540 回答
0

如果您只需要一个多维数组,您可以使用指针,调整大小将需要复制到新数组并删除旧数组,但您可以执行以下操作:

int** m;
int rows, cols;
cin >> rows >> cols;
m = new int* [rows];
for (int i = 0; i < rows; i++) {
    m[i] = new int [cols];
}

for (int i = 0; i < rows; i++) {
    delete [] m[i];
}
delete [] m;   

或者作为替代方案,您可以使用指向一维数组的指针,例如:

int* m;
int rows, cols;
cin >> rows >> cols;
m = new int [rows*cols];

并通过以下方式访问它:

for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
        m[i*cols+j] = i;

提供删除语句:

delete [] m;   
于 2014-02-07T13:03:32.333 回答