Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Both emplace_back and push_back are methods used to add an element to the end of a C++ vector. However, there are some differences:

  1. push_back takes an existing object while emplace_back constructs the object in place

The push_back method copies an existing object into the vector, while emplace_back constructs the new object in place, using its constructor arguments. For example, if Person is a class with a constructor that requires a name and age:

vector<Person> people;
people.emplace_back("Alice", 25); // constructs a new Person object directly in the vector
Person p("Bob", 30);
people.push_back(p); // copies an existing Person object into the vector
  1. emplace_back can be more efficient

emplace_back can be more efficient than push_back when dealing with complex objects. This is because it avoids creating a temporary object that needs to be copied into the vector. Instead, it constructs the new object directly in the vector's memory.

  1. emplace_back is more flexible

Since emplace_back constructs the object in place, it can be used to add elements of a variety of types (as long as they have a constructor that can be called with the given arguments). push_back, on the other hand, requires an object of the vector's type to be passed in.

In summary, emplace_back is a more efficient and flexible way to add elements to a C++ vector, especially for complex types. However, push_back is still useful when dealing with simple types or when you already have an existing object that you want to add to the vector.