C++ · Hash map · container
std::unordered_map<Key, T>
The standard hash map: average constant-time insert, find and erase, worst case linear.
#include <unordered_map> template<class Key, class T, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = …> class unordered_map;
C++23 (contains since C++20, insert_or_assign since C++17)
Operations
| Operation | Time | Worst case | Changes the collection |
|---|---|---|---|
| insert / emplace / insert_or_assign | O(1) | O(n) | Yes |
| operator[] / at | O(1) | O(n) | Yes |
| find / contains / count | O(1) | O(n) | No |
| erase | O(1) | O(n) | Yes |
"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.
How it works
- Representation
- Buckets of nodes (separate chaining is effectively required by the interface: bucket(), bucket_size() and stable element addresses). Rehashes when size() / bucket_count() exceeds max_load_factor() (default 1.0).
- Ordering
- Unspecified; changes on rehash. std::map keeps keys sorted.
- Duplicates
- Keys are unique (std::unordered_multimap allows duplicates).
- Mutability
- Mutable; keys inside the map are const.
- Memory and ownership
- One heap node per element plus the bucket array; references to elements stay valid across rehashes.
- Equality and comparison
- Hash (std::hash<Key> by default) and KeyEqual must agree: equal keys must hash equally.
Pitfalls
- operator[] inserts a default-constructed value when the key is missing, even if you only meant to read; use find, contains or at.
- Rehashing invalidates iterators (not references); inserting while iterating is unsafe.
- There is no std::hash for std::pair or your own types: provide a hash.
Alternatives
- std::map (sorted, O(log n), red-black tree in practice)
- std::flat_map (C++23, sorted vectors)
- std::vector of pairs + binary search for small read-mostly maps
In other languages
- C#: Dictionary<TKey, TValue>
- Python: dict
- Java: HashMap<K, V>