C++ std::vector emplace vs insert [duplicate]

2019-01-31 07:01发布

问题:

This question already has an answer here:

  • push_back vs emplace_back 6 answers

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

回答1:

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));


回答2:

insert copies objects into the vector.

emplace construct them inside of the vector.



标签: c++ vector stl