与唯一的指针构件初始化模板化基质类矢量矢量
问题描述:
template<class T>
class Matrix{
public:
Matrix();
~Matrix();
private:
std::unique_ptr<std::vector<std::vector<T> > > PtrToMyMatrix;
};
我有初始化PtrToMyMatrix
困难。假设构造函数只应将PtrToMyMatrix
指向一个T的1x1矩阵。我该怎么写?
我想这是一样的东西
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);
(ALLOC缺失)。
因此,您构建的外部vector
与1
内部vector
是用1
T
构造。
但是很少需要动态创建std::vector
,因为它已经动态存储其内部数据。你通常只是通过值来实例化它:
std::vector<std::vector<T> > MyMatrix(1, std::vector<T>(1));
这看起来像有两个间接太多。为什么不直接使用一个'vector'作为数据成员是否有原因? – dyp 2014-09-22 05:40:45
@dyp我的理由可能是没有根据的,因为我是初学者,但我的理由是我想让矩阵的内容从一个移到另一个。 – Kae 2014-09-22 05:43:14
@Karene你使用的是C++ 11还是C++ 03? – owensss 2014-09-22 05:45:56