std::unordered_map<Key, T> · C++

operator[] / at

operator[] returns the value, inserting a value-initialised one if the key is missing; at() throws instead.

T& operator[](const Key& key); T& at(const Key& key);

Complexity

AverageO(1)
Worst caseO(n)
Extra spaceO(1)

One lookup, plus an insert for operator[] on a missing key.

Tested example

std::unordered_map<std::string, int> counts;
counts["a"] += 1;              // missing key: inserts a value-initialised int (0) first
counts["a"] += 1;
assert(counts["a"] == 2);
(void)counts["typo"];          // reading through [] also inserts!
assert(counts.size() == 2);
bool threw = false;
try {
    (void)counts.at("nobody"); // at() never inserts; it throws
} catch (const std::out_of_range&) {
    threw = true;
}
assert(threw);
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/unordered_map_examples.cpp

Parameters

key
The key.

Behaviour

Returns
A reference to the mapped value.
Errors and preconditions
at(): std::out_of_range for a missing key.
Changes
operator[] may insert.
Memory and invalidation
operator[] may rehash (invalidating iterators).