Ask Your Question
0

What is the difference between emplace_back and push_back in C++ vectors?

asked 2023-03-31 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-14 07:00:00 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-31 11:00:00 +0000

Seen: 10 times

Last updated: May 14 '21