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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:41:50  来源:igfitidea点击:

C++ std::vector emplace vs insert

c++vectorstl

提问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

insertcopies objects into the vector.

insert将对象复制到向量中。

emplaceconstructthem inside of the vector.

emplace在向量内部构造它们。