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

find / contains / count

Looks a key up without inserting.

iterator find(const Key& key); bool contains(const Key& key) const; // C++20

Complexity

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

Hash and scan one bucket.

Tested example

std::unordered_map<std::string, int> ages{{"ada", 36}};
if (auto it = ages.find("ada"); it != ages.end()) assert(it->second == 36);
assert(ages.find("nobody") == ages.end());
assert(ages.contains("ada"));  // C++20
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
find: an iterator, or end(). contains: a bool. count: 0 or 1.
Errors and preconditions
None.
Changes
Nothing.
Memory and invalidation
No allocation.