C++ std::vector emplace vs insert

C++VectorStl

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

insert copies objects into the vector.

emplace construct them inside of the vector.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAditya SihagView Question on Stackoverflow
Solution 1 - C++juanchopanzaView Answer on Stackoverflow
Solution 2 - C++hate-engineView Answer on Stackoverflow