How do I use emplace vs push with std::unordered_map?

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.

Using 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.

Using 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.

Example of 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;
}

C++ std::unordered_map emplace insert performance container