std::unordered_map<Key, T> · C++
insert / emplace / insert_or_assign
Inserts a key only if absent (insert_or_assign overwrites).
std::pair<iterator, bool> insert(const value_type& value); template<class... Args> std::pair<iterator, bool> emplace(Args&&... args);
Complexity
| Average | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) per element |
Assumes: A hash that spreads keys over the buckets.
Hash the key, scan the bucket for an equal key, link a node. A rehash redistributes all n nodes but happens geometrically rarely.
Tested example
std::unordered_map<std::string, int> ages;
auto [it, inserted] = ages.insert({"ada", 36});
assert(inserted && it->second == 36);
auto [same, again] = ages.emplace("ada", 99); // key exists: nothing changes
assert(!again && same->second == 36);
ages.insert_or_assign("ada", 37); // C++17: insert or overwrite
assert(ages.at("ada") == 37);
Parameters
- value / args
- A key-value pair, or arguments to construct one.
Behaviour
- Returns
- An iterator to the element with that key and whether insertion happened.
- Errors and preconditions
- std::bad_alloc; exceptions from hashing or constructors (then the map is unchanged).
- Changes
- At most one new node; may rehash.
- Memory and invalidation
- A rehash invalidates all iterators; references and pointers to elements stay valid.