[英]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; }
// ...
};
类中有两个数据成员,其中一个是T
类型的指针。 我无法理解array< int, 2 >
dim
意味着什么。
成员变量dim
存储2D矩阵的第一维和第二维的大小Matrix< T >
。 这两个大小存储为array< int, 2 >
(我假设std::array< int, 2 >
:两个int
类型值的数组)。
如果没有此成员变量dim
, Matrix< 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;
声明一个长度为x的整数数组; 在你的情况下x是2。
这稍后用于存储矩阵的形状。
它是一个类型为array<int, 2>
的成员变量dim
的声明(可能是std::array
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.