【发布时间】:2019-10-22 07:53:18
【问题描述】:
这与我之前提出的关于在对向量上使用emplace_back 的问题有些相关。 emplace_back() vs push_back when inserting a pair into std::vector
现在我的问题是关于在向量向量上使用emplace_back。
这是我对 cmets 提出质疑的代码
std::vector<std::vector<int>> matrix;
matrix.emplace_back({1,2,3}); //doesn't compile
matrix.emplace_back(1,2,3); //doesn't compile
matrix.push_back({1,2,3}); //works and does what is expected (insert a vector made of {1,2,3} into matrix);
matrix.emplace_back(std::vector<int>{1,2,3}); //works but
//defeats the purpose of using emplace_back since this makes a copy
//and is thus equivalent to push_back in this case?
matrix.emplace_back(3,2) //this compiles,
//but it seems to insert a vector of size 3 made of 2s into the matrix.
//not actually sure why it does this
因此,由此看来,matrix.emplace_back(std::vector<int>{1,2,3}); 似乎是在向量向量上使用std::vector<T>::emplace_back 的唯一正确方法,但这似乎与push_back 相比没有任何优势。我对这个问题的理解正确吗?
另外,有人能解释一下为什么matrix.emplace_back(3,2) 在矩阵中插入一个由 2 组成的大小为 3 的向量吗?
【问题讨论】:
-
matrix.emplace_back(3,2)使用构造函数vector(std::size_t size, const T& value)。 -
@jarod42 糟糕,完全错过了。
标签: c++ vector stl push-back emplace