In C++, when using std::unordered_map
, both emplace
and push
(which is actually insert
) can be used to add elements to the map. However, there are differences in how they operate.
emplace
The emplace
function constructs an element in place, which means that it can create the element directly in the container without the need for copying or moving. This can lead to improved performance in certain scenarios.
insert
The insert
function adds an element to the map, which requires the creation of a temporary object that is then copied or moved into the container. This may involve additional overhead compared to emplace
.
emplace
vs insert
#include <unordered_map>
#include <string>
#include <iostream>
int main() {
std::unordered_map<:string int> myMap;
// Using emplace
myMap.emplace("One", 1);
// Using insert
myMap.insert(std::make_pair("Two", 2));
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
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?