C++20 sections · 1024 units
Open in Course

Erasing from Sets

How to delete

Use s.erase(value) to remove an element by its value. The method returns the number of elements removed, which is 0 if the value wasn't in the set or 1 if it was deleted. Erase by iterator: s.erase(s.find(value)) removes at a specific position.

Be careful: erasing s.end() is undefined behavior. Always check that find succeeded before erasing. Erase a range: s.erase(s.begin(), s.find(10)) removes all elements less than 10. This runs in O(k+logn)O(k + \log n) where k is the number of elements removed from the set.