【问题标题】:What does array<int,2> dim mean in this piece of code?这段代码中的 array<int,2> dim 是什么意思?
【发布时间】:2018-08-14 16:23:05
【问题描述】:

我在阅读 The c++ Programming Language 4th edition 时遇到了这段代码

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&lt; int, 2 &gt; dim 是什么意思。

【问题讨论】:

    标签: c++ arrays c++11 templates copy-constructor


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      array&lt;int,N&gt; x;

      声明一个长度为 N 的整数数组;在你的情况下,N 是 2。

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

      【讨论】:

        【解决方案3】:

        这是array&lt;int, 2&gt;类型的成员变量dim的声明(可能是std::array。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-28
          • 1970-01-01
          • 2011-04-12
          相关资源
          最近更新 更多