c ++向量emplace_back更快? [英] c++ vector emplace_back is faster?
问题描述
如果我有一个类
class foo {
public:
foo() { // spend some time and do something. }
private:
// some data here
}
现在我有一个foo的向量,我想把这个向量放入另一个向量
Now I have a vector of foo, I want to put this vector into another vector
vector<foo> input; // assume it has 5 elements
vector<foo> output;
这两行有什么性能差异吗?
Is there ANY performance difference with these two lines?
output.push_back(input[0])
output.emplace_back(input[0])
推荐答案
这两行是否有性能差异?
Is there ANY performance difference with these two lines?
否,两者都将使用复制构造函数初始化新元素。
No, both will initialise the new element using the copy constructor.
emplace_back
可能会在构造多于(或少于)一个参数时产生效益:
emplace_back
can potentially give a benefit when constructing with more (or less) than one argument:
output.push_back(foo{bar, wibble}); // Constructs and moves a temporary
output.emplace_back(bar, wibble); // Initialises directly
emplace的真正好处
在性能上不是那么多,而是允许在容器中创建不可复制(以及在某些情况下不可移动)的元素。
The true benefit of emplace
is not so much in performance, but in allowing non-copyable (and in some cases non-movable) elements to be created in the container.
这篇关于c ++向量emplace_back更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!