Comparisions of push_back and emplace_back in C++ std::vector


In C++, both push_back and emplace_back are methods of the std::vector class used to add elements to the end of the vector, but they have some differences in how they handle the elements.

push_back

Usage: push_back(const T& value) or push_back(T&& value)
Behavior: This method copies (or moves) the value into the vector.
Overhead: Involves an extra copy or move operation if the element is not already in-place.

Example:

std::vector<int> vec;
int value = 10;
vec.push_back(value); // Copy value into the vector
vec.push_back(20);   // Move 20 into the vector

emplace_back

Usage: emplace_back(Args&&… args)
Behavior: Constructs the element in-place at the end of the vector using the provided arguments. It does not involve a copy or move operation.
Efficiency: Potentially more efficient because it constructs the object directly in the vector, avoiding unnecessary copies or moves.

Example:

std::vector<int> vec;
vec.emplace_back("Hello");    // Directly constructs a std::string in the vector
vec.emplace_back(5, 'a');     // Directly constructs a std::string with 5 'a' characters

When to Use Which

Use push_back when you have an existing object that you want to add to the vector, and you’re okay with an extra copy or move operation.

Use emplace_back when you want to construct an object directly in the vector, especially if the construction involves parameters or if you want to avoid the cost of copying or moving.

In general, emplace_back is preferred for efficiency and when working with complex objects. Use emplace_back whenever you can – this will construct the object in place and avoid memory copy (move) rather than copy.

C/C++ Programming

–EOF (The Ultimate Computing & Technology Blog) —

377 words
Last Post: C++: Access a Non-existent Key in std::map or std::unordered_map
Next Post: Modern C++ Language Features

The Permanent URL is: Comparisions of push_back and emplace_back in C++ std::vector (AMP Version)

Leave a Reply