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
| Average | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(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);
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.