使用指向向量向量的唯一指针成员初始化模板化矩阵类

Initializing templated matrix class with unique pointer member to vector of vectors

本文关键字:向量 初始化 指针 唯一 成员      更新时间:2023-10-16

我有

template<class T>
class Matrix{
public:
Matrix();
~Matrix();
private:
std::unique_ptr<std::vector<std::vector<T> > > PtrToMyMatrix;
};

我在初始化PtrToMyMatrix时遇到困难。假设构造函数只应放入一个指向 T 的 1x1 矩阵PtrToMyMatrix指针。我怎么写这个?

我想它是这样的

Matrix<T>::Matrix():PtrToMyMatrix(//Here it goes the value
){};

在值的位置,我想它应该像

new std::unique_ptr<vector<vector<T> > >(// Here a new matrix
)

代替新矩阵,我想它是这样的

new vector<vector<T> >(// Here a new vector
)

代替新矢量

new vector<T>(new T())

应该怎么样?

我认为你在追求这个:

std::unique_ptr<std::vector<std::vector<T> > >
    PtrToMyMatrix(new std::vector<std::vector<T> >(1, std::vector<T>(1)));

构造函数std::vector(size_type n, const value_type& val);(缺少分配(。

因此,您用1构造的内vector构造外vector,该内用1 T构造。

但是,很少需要动态创建std::vector,因为它已经动态地存储其内部数据。您通常只需按值实例化它:

std::vector<std::vector<T> > MyMatrix(1, std::vector<T>(1));