std::unordered_set<Key> · C++

insert / emplace

Inserts an element if absent.

std::pair<iterator, bool> insert(const value_type& value);

Complexity

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

Assumes: Good hash.

Hash, scan the bucket, link a node.

Tested example

std::unordered_set<int> seen;
assert(seen.insert(4).second);    // inserted
assert(!seen.insert(4).second);   // already present: unchanged
assert(seen.size() == 1);
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/unordered_set_examples.cpp

Parameters

value
The element.

Behaviour

Returns
An iterator to the element and whether it was inserted.
Errors and preconditions
std::bad_alloc; exceptions from hashing (map unchanged).
Changes
At most one new node; may rehash.
Memory and invalidation
Rehash invalidates iterators, not references.