C 中的多维数组的分配,部分为可变长度

Allocation for multidimension array, partially of variable length, in C++

本文关键字:数组 分配      更新时间:2023-10-16

假设我有一个多维数组,在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 标准的一部分?

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])

没有C 标准中具有可变长度的多维数组,但是您可以轻松地用其中的向量编写自己的矩阵类,该矢量用'row_index*row_index*rowlength*rowlength columan_index'计算向量索引。

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

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;   

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

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;   

没有默认容器,如果只需要一个分配,则需要编写一个。这是我可以给出的最短示例:

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;

请注意,将这些元素分配在一个向量中,并在xy上找到一个元素,我使用y * width + x在向量中获取索引。

也已经为此目的实施了,因此最好从互联网上拿走一个。您可以查看Boost库中的所在。