Home c++ Difference between push_back and emplace_back

Difference between push_back and emplace_back




Tell me what is the difference between the good old vector :: push_back () and the new standard vector :: emplace_back () ?

Answer 1, authority 100%

push_back adds a copy of the object (or provides movement if possible), and emplace_back creates an object directly at the end of the vector, i.e. without unnecessary copying (or moving).

Answer 2, authority 92%

Simpler with an example …

struct Item
  int a, b, c;
  Item (int a, int b, int c): a (a), b (b), c (c) {}
int main (int argc, const char * argv [])
  vector & lt; Item & gt; x;
  // x.push_back (1,2,3); & lt; - won't compile!
  x.emplace_back (1,2,3);

As you can see, push_back ‘needs an item type object (or a redundant one). But emplace ‘is simply passed arguments, as constructor .

P.S. It is clear that this constructor can also be a copy constructor 🙂 So

x.emplace_back (Item (0,1,2));

works too.

Answer 3

x.push_back ({1,2,3}); // Works

I would say push_back is more versatile. With emplace_back, there are nuances in more complex algorithms. For example, when copying elements of a multidimensional vector to a one-dimensional one. It looks like it works, but when you compile it, it swears. I would say they complement one another. If emplace_back works, we leave it, and if wonderful errors come up, then put push_back and add {} as I showed above.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions