[英]push_back a vector of vectors into a vector
如何創建矩陣的向量(向量的向量),其中矩陣具有不同的大小並已初始化?
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);
編譯錯誤:
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);
^
您需要使用以下內容:
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));
將類型Vector
更改為:
typedef std::vector<std::unique_ptr<Matrix>> Vector;
然后你可以push_back
它,
v.push_back(std::move(m));
順便說一句: (*m)[0][0] = 1.0;
是UB。 您可以使用push_back
添加元素。
這樣安排你的typedefs
:
typedef std::vector<std::vector<double>> Matrix;
typedef std::vector<std::shared_ptr<Matrix>> Vector;
請注意shared_ptr
的使用 - 這使得將Matrix
所有權轉移到Vector
變得更加容易。
然后:
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.