In C++, the `std::vector` container provides two primary methods for adding elements: `push_back` and `emplace_back`. While both can be used to insert elements into a vector, they behave differently regarding how the elements are constructed and added to the container.
The `push_back` method adds a copy of an object to the end of the vector. If you pass an object to `push_back`, it will create a copy, which can involve overhead.
The `emplace_back` method, on the other hand, constructs the object in-place. This means it forwards the arguments directly to the constructor of the object being added, leading to potentially better performance since it avoids the extra copy or move operation.
#include <iostream>
#include <vector>
class MyClass {
public:
MyClass(int x) : value(x) {
std::cout << "Constructing MyClass with value: " << value << std::endl;
}
int value;
};
int main() {
std::vector vec;
vec.push_back(MyClass(10)); // Copy construction
vec.emplace_back(20); // In-place construction
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?