73

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

Aditya Sihag
  • 5,057
  • 4
  • 32
  • 43

2 Answers2

170

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
  • 223,364
  • 34
  • 402
  • 480
  • 18
    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
53

insert copies objects into the vector.

emplace construct them inside of the vector.

hate-engine
  • 2,300
  • 18
  • 26
  • 15
    Note that in C++11 `insert` does not have to copy, it can also move. – juanchopanza Feb 09 '13 at 12:47
  • 19
    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