C 中的多维数组的分配,部分为可变长度
Allocation for multidimension array, partially of variable length, in C++
假设我有一个多维数组,在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;
请注意,将这些元素分配在一个向量中,并在x
和y
上找到一个元素,我使用y * width + x
在向量中获取索引。
也已经为此目的实施了,因此最好从互联网上拿走一个。您可以查看Boost库中的所在。
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 如何通过 malloc 为队列数组分配内存?
- 具有动态数组分配的OpenMP嵌套循环
- 如何为数组结构的数组分配内存
- 如何为结构数组分配内存?
- cpp 数组 - 分配常量索引有效,而非常量索引不起作用
- 如何为字符指针数组分配内存?
- 在 C++ 中初始化后的数组分配
- 将数据分配给了数组分配,但程序显示了以缓冲区超支的输出
- C++函数问题中的数组分配
- 子数组分配:使用聚合对象错误的预期"{...}"进行初始化
- 为什么我的指针数组分配不起作用
- std::堆栈和堆栈溢出错误的数组分配
- 在 c++ 中是否有通过声明"implicit"数组分配?
- 在 c++ 中为 2-D "Dynamically Created"数组分配值时遇到问题
- 如何为C++数组分配指向第一个元素的指针
- 字符数组分配
- 将数组分配在固定数量的线程之间
- 为构造函数中的数组分配值