Section

std::unordered_map

std::unordered_map is an associative container that stores key-value pairs with unique keys.

Elements are organized into buckets according to the hash of the key, so lookup, insertion, and erasure have average constant-time complexity.

# Declarations

template<
class Key,
class T,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>
> class unordered_map;

(since C++11)

namespace pmr {
template<
class Key,
class T,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>
> using unordered_map =
std::unordered_map<Key, T, Hash, KeyEqual,
std::pmr::polymorphic_allocator<std::pair<const Key, T>>>;
}

(since C++17)

# Template parameters

  • Key: key type.
  • T: mapped value type.
  • Hash: hash function object used to place keys into buckets. Equivalent keys must produce the same hash value.
  • KeyEqual: equality predicate used to test whether two keys are equivalent.
  • Allocator: allocator used to manage the stored std::pair<const Key, T> objects. It must satisfy the Allocator requirements.

# Semantics

unordered_map meets the requirements of Container, AllocatorAwareContainer, and UnorderedAssociativeContainer.

Keys are unique: for any key-equivalence class, at most one element is present.

Hash-based lookup relies on both Hash and KeyEqual. If KeyEqual(a, b) is true, then Hash(a) and Hash(b) must yield the same value.

Iteration order is not sorted and does not have the stability guarantees of ordered associative containers such as std::map. Rehashing may move elements between buckets and change iteration order.

# Example

#include <iostream>
#include <string>
#include <unordered_map>
 
int main()
{
    std::unordered_map<std::string, int> word_count{
        {"red", 2},
        {"green", 4},
        {"blue", 1}
    };
 
    word_count["red"] += 1;
    word_count["black"] = 3;
 
    for (const auto& [word, count] : word_count)
        std::cout << word << ": " << count << '\n';
}

This is the typical unordered_map usage pattern: key-based lookup with unique keys, average constant-time updates, and no meaningful sort order.

# Member types

Member typeDefinition
key_typeKey
mapped_typeT
value_typestd::pair<const Key, T>
size_typeUnsigned integer type, usually std::size_t
difference_typeSigned integer type, usually std::ptrdiff_t
hasherHash
key_equalKeyEqual
allocator_typeAllocator
referencevalue_type&
const_referenceconst value_type&
pointerallocator-aware pointer to value_type
const_pointerallocator-aware pointer to const value_type
iterator, const_iteratorForward iterators over the whole container
local_iterator, const_local_iteratorForward iterators within one bucket
node_typeNode handle for extracted elements (C++17)
insert_return_typeReturn type for node-handle insertion (C++17)

# Iterator invalidation

OperationInvalidation
Read-only operations, swapNever invalidate iterators to existing elements
clear, rehash, reserve, operator=Always invalidate all iterators
insert, emplace, operator[], insert_or_assign, try_emplaceInvalidate iterators only if the operation causes rehashing
eraseInvalidates only iterators and references to the erased element

The end() iterator is invalidated by swap, even though iterators referring to elements remain valid.

References and pointers to stored key-value pairs remain valid across rehashing and swap; they are invalidated only when the referenced element is erased.

# Reference map

AreaKey entries
Construction and lifetimeunordered_map::unordered_map, unordered_map::~unordered_map, unordered_map::operator=, get_allocator
Iteratorsbegin, cbegin, end, cend, bucket begin, cbegin, bucket end, cend
Capacityempty, size, max_size
Modifiersclear, insert, insert_range, insert_or_assign, emplace, emplace_hint, try_emplace, erase, swap, extract, merge
Lookupat, operator[], count, find, contains, equal_range
Bucket interfacebucket_count, max_bucket_count, bucket_size, bucket
Hash policy and observersload_factor, max_load_factor, rehash, reserve, hash_function, key_eq
Non-member functionscomparison operators, std::swap(std::unordered_map), erase_if

# Deduction guides

The class has deduction guides so constructor arguments can infer Key, T, and related policy types where the selected constructor permits it.

# Notes

unordered_map is usually the right default when keys are unique and fast average-case lookup matters more than sorted traversal.

If stable ordering, lower-bound queries, or ordered iteration are important, std::map is the better fit.

# Feature-test macros

MacroValueStdFeature
__cpp_lib_containers_ranges202202LC++23ranges construction and insertion for containers

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2050C++11the definitions of reference, const_reference, pointer, and const_pointer were based on allocator_typebased on value_type and std::allocator_traits

# See also