std::unordered_set<Key> · C++

contains / find / count

Tests membership.

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

Complexity

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

Hash the key and scan the elements of one bucket.

Tested example

std::unordered_set<std::string> words{"apple", "pear"};
assert(words.contains("apple"));  // C++20; before that: words.count(x) != 0
assert(!words.contains("Apple"));
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/unordered_set_examples.cpp

Parameters

key
The element.

Behaviour

Returns
A bool (find returns an iterator, count 0 or 1).
Errors and preconditions
None.
Changes
Nothing.
Memory and invalidation
No allocation.