简体   繁体   English

数组<int,2> dim在这段代码中意味着什么?

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

I came across this piece of code while reading The c++ Programming Language 4th edition 我在阅读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; }
    // ...
};

There are two data members in the class of which one is a pointer of type T . 类中有两个数据成员,其中一个是T类型的指针。 I am not able to understand what array< int, 2 > dim means. 我无法理解array< int, 2 > dim意味着什么。

The member variable dim stores the size of the first and second dimension of your 2D matrix, Matrix< T > . 成员变量dim存储2D矩阵的第一维和第二维的大小Matrix< T > Those two sizes are stored as an array< int, 2 > (I assume std::array< int, 2 > : an array of two values of type int ). 这两个大小存储为array< int, 2 > (我假设std::array< int, 2 > :两个int类型值的数组)。

Without this member variable dim , Matrix< T > has no idea how many elements are contained in its heap-allocated array elem ( note that elem is a pointer to the first element contained in the array of contiguous elements). 如果没有此成员变量dimMatrix< T >不知道其堆分配的数组elem中包含多少个元素( 请注意elem是指向包含在连续元素数组中的第一个元素的指针)。 So Matrix< T > has no way of safely iterating these elements, since it would not know when to stop. 因此Matrix< T >无法安全地迭代这些元素,因为它不知道何时停止。 (In fact the only useful operation Matrix< T > can perform, is deallocating the heap-allocated array, as is the case in your destructor.) Therefore, the size of the heap-allocated array (ie dim[0] * dim[1] ) is explicitly stored as well. (事实上​​, Matrix< T >可以执行的唯一有用的操作是释放堆分配的数组,就像析构函数中的情况一样。)因此,堆分配的数组的大小(即dim[0] * dim[1] )也被明确存储。

This is making use of the std::array from the standard library. 这是利用标准库中的std :: array。 You can find a detailed reference here: https://en.cppreference.com/w/cpp/container/array 您可以在此处找到详细的参考: https//en.cppreference.com/w/cpp/container/array

array<int,N> x;

declares an array of integers of length x; 声明一个长度为x的整数数组; x is 2 in your case. 在你的情况下x是2。

This is later used to store the shape of your matrix. 这稍后用于存储矩阵的形状。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM