In C++, std::unordered_set::erase()removes values from the unordered_set. You can give it a value, an iterator to one element, or a pair of iterators for a range.
Erasing by value is safe even when the value is not in the unordered_set. It just returns 0. Values stay unique and hash-bucket order can change after removals. Include <unordered_set> to use it.
This is a member of std::unordered_set<T>, a hash table of unique values. Find, insert, and erase are usually average constant time. Unlike std::set, values are not sorted and iteration order is unspecified. Elements are const, so you cannot change a stored value through an iterator. There is no operator[] and no at(). Prefer find() or contains() to look up a value, and call reserve() before many inserts.
Syntax
Pass a value, an iterator, or a range.
C++
std::size_t n = s.erase(30); // by value: 1 or 0
auto next = s.erase(s.find(20)); // by iterator
s.erase(s.find(40)); // remove one value
Call
What it does
s.erase(value)
Removes the value if it exists. Returns 1 if it was removed and 0 if it was not found.
s.erase(pos)
Removes the element that pos points to. Returns an iterator to the next element.
s.erase(first, last)
Removes every element from first up to, but not including, last. Returns last.
Never call erase(pos) with end(), because it points to no element. To erase while you loop, always use the iterator that erase() returns. An unordered_set does not move other values when one is removed, so all other iterators stay valid.
The for loop has no ++it in its header. The loop moves forward by itself inside the body.
When the value is even, it = s.erase(it) removes it and moves it to the next element. When the value is odd, ++it moves on without removing anything.
Each step moves forward exactly once, so no element is skipped and no removed iterator is used. Four odd values remain; membership checks prove 2 is gone.
Frequently Asked Questions
The value form returns how many values were removed, which is 0 or 1 for an unordered_set. The iterator forms return an iterator to the element after the removed one.
Nothing happens. erase() returns 0 and the unordered_set is unchanged. It does not throw.
Use the returned iterator: it = s.erase(it). Do not use the old iterator after erasing, because that element is gone.
Yes, but check that the iterator is not end() first. Erasing end() is undefined behavior. Erasing by value is simpler when you do not need the iterator.
erase() removes chosen values. clear() removes all of them and leaves an empty unordered_set.