C++ std::vector emplace 与插入

2021-12-21 00:00:00 vector c++ stl

我想知道两者之间有什么区别.我注意到 emplace 是 c++11 加法.那么为什么要添加?

I was wondering what are the differences between the two. I notice that emplace is c++11 addition. So why the addition ?

推荐答案

Emplace 接受构建对象所需的参数,而 insert 接受(引用)一个对象.

Emplace takes the arguments necessary to construct an object in place, whereas insert takes (a reference to) an object.

struct Foo
{
  Foo(int n, double x);
};

std::vector<Foo> v;
v.emplace(someIterator, 42, 3.1416);
v.insert(someIterator, Foo(42, 3.1416));

相关文章