In C++, std::unordered_map::insert()adds a new pair to a std::unordered_map. The pair is placed into a hash bucket. Keys stay unique, but not sorted.
If the key is already in the unordered_map, insert() does nothing and the old value stays. The m[key] = value form is different: it creates the key if needed and always overwrites the value. 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 a pair, a braced pair, an initializer list, or a range of pairs.
C++
auto r = m.insert({"one", 1}); // one pair
m.insert(std::make_pair("two", 2)); // pair made with make_pair
m.insert({{"c", 3}, {"d", 4}}); // initializer list
m.insert(other.begin(), other.end()); // a range of pairs
Call
What it does
m.insert(pair)
Adds the pair if its key is new. Returns std::pair<iterator, bool>.
m.insert(hint, pair)
Same, but uses hint as a starting position to be faster. Returns an iterator.
m.insert(first, last)
Inserts every pair from the range. Pairs with keys that already exist are skipped.
m.insert({p1, p2, ...})
Inserts all pairs in the initializer list, skipping duplicate keys.
m.insert(std::move(node))
Inserts a node handle from extract() (C++17).
Since C++17 you also have insert_or_assign() to update existing values and try_emplace() to avoid wasted work. emplace() builds the pair in place.
insert({"x", 2}) is ignored because "x" exists, so x keeps the value 1.
m["y"] = 2 overwrites the earlier 1, because the bracket operator assigns every time.
m["q"] does not find "q", so it inserts it with the default 0 even though you only read it. That is why the size is 3 and q=0 appears.
Frequently Asked Questions
The single-pair form returns std::pair<iterator, bool>. The iterator points at the pair with that key, and the bool is true only if a new pair was added.
Nothing. The unordered_map is not changed and the old value stays. The returned bool is false.
insert() adds only new keys and keeps old values. m[key] = value adds the key if needed and always sets the value. Also, m[key] on a missing key inserts a default value even when you only read it.
Use m[key] = value, m.at(key) = value, or insert_or_assign() in C++17. insert() will not update it.
No. unordered_map does not sort keys. Iteration order is unspecified.