In C++11, std::unordered_map::emplace()builds a new pair directly inside the unordered_map from the arguments you pass. You do not make a pair yourself first, so a copy or move can be avoided.
Like insert(), it adds the pair only if the key is new. If the key exists, the unordered_map is not changed. Include <unordered_map> to use it.
This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Pass the arguments for the key and the value, in that order.
C++
auto r = m.emplace(3, "three"); // key 3, value "three"
bool added = r.second; // true if the key was new
Call
What it does
m.emplace(args...)
Constructs a pair from args. Returns std::pair<iterator, bool>.
emplace() may build the pair before it checks the key. If the key exists, that pair is destroyed again. When you want no wasted work, use try_emplace() (C++17).
The loop visits each name with its index i (0, 1, 2).
ids.emplace(i + 1, names[i]) makes a pair with the key i + 1 and a copy of the name, directly inside the unordered_map.
The keys 1, 2, 3 are already in order, so the final loop prints the names in the same order as the vector.
Frequently Asked Questions
It constructs a new key and value pair inside the unordered_map from the arguments you pass. If the key already exists, it does not change the unordered_map.
insert() takes a ready pair. emplace() takes the arguments for the pair and builds it in place, which can avoid a copy or move.
No. If the key exists, the old value stays and the returned bool is false. Use insert_or_assign() to update.
C++11.
Use try_emplace() (C++17) when building the value is costly or when you pass something you moved. It does not touch the arguments if the key exists.