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

erase

Removes by key or by iterator.

size_type erase(const Key& key); iterator erase(const_iterator pos);

Complexity

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

Find the node and unlink it; no rehash on erase.

Tested example

std::unordered_map<std::string, int> ages{{"ada", 36}, {"bob", 25}};
assert(ages.erase("bob") == 1);  // returns the number of elements removed
assert(ages.erase("bob") == 0);
assert(ages.size() == 1);
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/unordered_map_examples.cpp

Parameters

key / pos
What to remove.

Behaviour

Returns
erase(key): number removed (0 or 1). erase(pos): iterator to the next element.
Errors and preconditions
erase(pos) with an invalid iterator is undefined behaviour.
Changes
Destroys one node.
Memory and invalidation
Invalidates only iterators and references to the erased element.