[英]push_back a vector of vectors into a vector
How to create a vector of matrices (vector of vectors) where the matrices are of different size and initialized?如何创建矩阵的向量(向量的向量),其中矩阵具有不同的大小并已初始化?
typedef std::vector<double> Vector;
typedef std::vector<std::vector<double>> Matrix;
Vector v;
std::unique_ptr<Matrix> m = std::make_unique<Matrix>();
(*m)[0][0] = 1.0;
v.push_back(m);
Compilation error:编译错误:
vectors.cpp: In function 'int main()':
vectors.cpp:37:18: error: no matching function for call to 'std::vector<double>::push_back(std::uniq
ue_ptr<std::vector<std::vector<double> > >&)'
v.push_back(m);
^
You need to use something along the lines of:您需要使用以下内容:
typedef std::vector<std::vector<double>> Matrix;
typedef std::vector<std::unique_ptr<Matrix>> MatrixVector;
std::unique_ptr<Matrix> m = std::make_unique<Matrix>();
MatrixVector mv;
mv.push_back(std::move(m));
Change type Vector
to:将类型
Vector
更改为:
typedef std::vector<std::unique_ptr<Matrix>> Vector;
then you can push_back
it,然后你可以
push_back
它,
v.push_back(std::move(m));
BTW: (*m)[0][0] = 1.0;
顺便说一句:
(*m)[0][0] = 1.0;
is UB.是UB。 You might use
push_back
to add element.您可以使用
push_back
添加元素。
Arrange your typedefs
thus:这样安排你的
typedefs
:
typedef std::vector<std::vector<double>> Matrix;
typedef std::vector<std::shared_ptr<Matrix>> Vector;
Note the use of shared_ptr
- this makes it easier to transfer ownership of the Matrix
into the Vector
.请注意
shared_ptr
的使用 - 这使得将Matrix
所有权转移到Vector
变得更加容易。
Then:然后:
Vector v;
std::shared_ptr<Matrix> m = std::make_shared<Matrix>();
// Add content to the matrix...
v.push_back(m);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.