array<int,2> dim 在这段代码中是什么意思?

What does array<int,2> dim mean in this piece of code?

我在阅读《C++ 程序设计语言》第 4 版时偶然发现了这段代码

template<class T>
class Matrix {
    array<int,2> dim; // two dimensions

    T∗ elem; // pointer to dim[0]*dim[1] elements of type T

public:
    Matrix(int d1, int d2) :dim{d1,d2}, elem{new T[d1∗d2]} {} // error handling omitted

    int size() const { return dim[0]∗dim[1]; }

    Matrix(const Matrix&); // copy constructor

    Matrix& operator=(const Matrix&); // copy assignment

    Matrix(Matrix&&); // move constructor

    Matrix& operator=(Matrix&&); // move assignment

    ˜Matrix() { delete[] elem; }
    // ...
};

class中有两个数据成员,其中一个是T类型的指针。我无法理解 array< int, 2 > dim 的意思。

array<int, 2>类型的成员变量dim的声明(可能是std::array。)

成员变量dim存储二维矩阵的第一维和第二维的大小,Matrix< T >。这两个大小存储为 array< int, 2 >(我假设 std::array< int, 2 >:两个类型为 int 的值的数组)。

如果没有这个成员变量dimMatrix< T >不知道它的堆分配数组中包含多少元素elem注意 elem 是指向连续元素数组中包含的第一个元素的指针)。所以 Matrix< T > 无法安全地迭代这些元素,因为它不知道何时停止。 (实际上,Matrix< T > 可以执行的唯一有用操作是释放分配给堆的数组,就像在析构函数中的情况一样。)因此,分配给堆的数组的大小(即 dim[0] * dim[1])也被显式存储。

这是利用标准库中的 std::array。您可以在此处找到详细参考:https://en.cppreference.com/w/cpp/container/array

array<int,N> x;

声明一个长度为N的整数数组;在你的例子中 N 是 2。

稍后用于存储矩阵的形状。