C++ std::vector emplace 与插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14788261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ std::vector emplace vs insert
提问by Aditya Sihag
I was wondering what are the differences between the two. I notice that emplace is c++11 addition. So why the addition ?
我想知道两者之间有什么区别。我注意到 emplace 是 c++11 加法。那么为什么要添加呢?
回答by juanchopanza
Emplace takes the arguments necessary to construct an object in place, whereas insert takes (a reference to) an object.
Emplace 接受构建对象所需的参数,而 insert 接受(引用)一个对象。
struct Foo
{
Foo(int n, double x);
};
std::vector<Foo> v;
v.emplace(someIterator, 42, 3.1416);
v.insert(someIterator, Foo(42, 3.1416));
回答by hate-engine
insert
copies objects into the vector.
insert
将对象复制到向量中。
emplace
constructthem inside of the vector.
emplace
在向量内部构造它们。