[英]How to declare 2D dynamic array in C++
如何声明一个二维数组,其中行是动态的,但行长是固定的? 如果行和行的长度都是动态的,有没有办法做到这一点?
PS 我不能使用 STL 容器或 class 字符串。
您可以为此使用std::vector
和std::array
。
std::vector
是一个动态长度数组。
std::array
是一个固定长度的数组,用作
array<int, 20> arr;
arr[10] = 42;
array<int, 20> anotherArr = arr; // copied here, as opposed to C arrays
int oldStyleArr[20];
oldStyleArr[10] = 42;
// int newStyleArr[20] = oldStyleArr; // error here
它是 C 样式数组的便捷包装器,并提供值语义和各种便捷方法,如size()
。
因此,您可以为包含 20 个int
动态向量的数组创建array<vector<int>, 20>
或为固定长度 arrays 的动态向量创建vector<array<int, 20>>
。
UPD: std::array
仅适用于编译时已知的数组边界。 如果您的数组边界仅在运行时已知,您仍然可以从大小和(可选)元素中使用std::vector
的构造函数:
int rowCount, columnCount;
cin >> rowCount >> columnCount;
using Row = vector<int>;
// create `vector` of `rowCount` rows,
// where each row is `vector` of `columnCount` ints
vector<Row> arr2d(rowCount, Row(columnCount));
但是,这不是最有效的解决方案,因为每一行都是单独分配的。 你可以用一个一维vector
的小包装来解决这个问题:
template<class T>
class Vector2D {
public:
Vector2D(int rows, int cols)
: data(rows*cols)
, rows(rows)
, cols(cols) {}
int rowCount() const { return rows; }
int columnCount() const { return cols; }
T& get(int r, int c) { return data[r*cols + c]; }
T const& get(int r, int c) const { return data[r*cols + c]; }
void addRow() {
data.resize(cols*(rows + 1));
}
// ...
private:
vector<T> data;
int rows;
int cols;
};
您可以将std::vector
用于动态范围 arrays。 您需要实例化 arrays 的向量来实现此目的。
只需声明一个一维数组并自己计算索引,就像编译器如何生成对多维数组的访问一样。 每行都有width
项,因此[x][y]
元素将具有索引x*width + y
template<typename T>
class twoD
{
const int width;
const int height;
T* data;
twoD(int w, int h) : width(w), height(h)
{
data = new T[width*height];
}
~twoD()
{
delete[] data;
}
T& at(int x, int y)
{
return data[x*width + y];
}
T const& at(int x, int y) const
{
return data[x*width + y];
}
}
twoD myArray(4, 8);
myArray.at(2, 3) = 5;
myArray.at(4, 5) = 6 - myArray.at(2, 3);
同样的方法可用于任意程度访问多维arrays
您正在寻找的可能是: std::vector<std::array<int, 20>> arr;
但是,如果 STL 容器不是一个选项,您可能需要自己实现容器。 链表可能是最容易实现的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.