C++ list erase() Function
Example
Remove the second element of a list:
list<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
list<string>::iterator it = cars.begin();
++it;
cars.erase(it);
for (string car : cars) {
cout << car << "\n";
}
Definition and Usage
The erase() function removes one element, or a range of elements, from a list. The elements to remove are given with iterators (objects that point to elements).
A list iterator cannot jump forward with +, like cars.begin() + 1. Instead, use ++ to move it one step at a time. In the example, it moves from the first element to the second element (BMW).
The erase function is defined in the <list> header file.
Syntax
list.erase(iterator position);
list.erase(iterator start, iterator end);
Use the first form to remove one element, and the second form to remove a range of elements.
Parameter Values
| Parameter | Description |
|---|---|
| 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: | An iterator pointing to the element after the removed elements. If the removed elements were at the end, it is the same as list.end(). |
|---|
Related Pages
Read more about lists in our List Tutorial.