簡體   English   中英

數組<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; }
    // ...
};

類中有兩個數據成員,其中一個是T類型的指針。 我無法理解array< int, 2 > dim意味着什么。

成員變量dim存儲2D矩陣的第一維和第二維的大小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;

聲明一個長度為x的整數數組; 在你的情況下x是2。

這稍后用於存儲矩陣的形狀。

它是一個類型為array<int, 2>的成員變量dim的聲明(可能是std::array 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM