C++ set erase() Function
Example
Remove "Volvo" from a set:
set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.erase("Volvo");
for (string car : cars) {
cout << car << "\n";
}
Definition and Usage
The erase() function removes one or more elements from a set.
You can remove an element by its value, or by an iterator that points to it. You can also remove all elements between two iterators.
The erase function is defined in the <set> header file.
Tip: Use clear() to remove all elements.
Syntax
set.erase(type value)
set.erase(iterator position)
set.erase(iterator start, iterator end)
Use one of the three forms above. type is the type of the elements in the set, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The value of the element to remove. |
| position | Required. An iterator pointing to the element to remove. |
| start | Required. An iterator pointing to the first element to remove. |
| end | Required. An iterator pointing to the position after the last element to remove. The element at this position is not removed. |
Technical Details
| Returns: | When you remove by value: the number of elements removed (1 or 0). When you remove by iterator: an iterator to the element after the last removed element. |
|---|
Related Pages
Read more about sets in our Sets Tutorial.