69

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

Aditya Sihag
  • 4,959
  • 4
  • 30
  • 41

2 Answers2

159

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));
juanchopanza
  • 216,937
  • 30
  • 383
  • 461
  • 13
    Although the question is marked duplicate, this answer clarifies things for me MUCH better then the answers to the "original". – JHBonarius Jul 08 '18 at 10:29
51

insert copies objects into the vector.

emplace construct them inside of the vector.

hate-engine
  • 2,260
  • 17
  • 26
  • 14
    Note that in C++11 `insert` does not have to copy, it can also move. – juanchopanza Feb 09 '13 at 12:47
  • 17
    It's worth mentioning that while insert may move if it an rvalue cast is used, it may not. Hence, Scott Meyer's recommendation to use emplace whenever possible for performance clarity. – jeremyong Dec 06 '13 at 23:37