c++list erase
时间: 2023-09-27 09:12:08 浏览: 96
The `erase` function in C++ is used to remove elements from a list container. It takes one or two arguments:
1. Iterator: This is the position of the element to be removed.
2. Iterator range: This is a range of elements to be removed, specified by two iterators.
The syntax for using the `erase` function is as follows:
```
list_name.erase(iterator_position);
list_name.erase(starting_iterator, ending_iterator);
```
Here, `list_name` is the name of the list container, `iterator_position` is the position of the element to be removed, and `starting_iterator` and `ending_iterator` are the iterators specifying the range of elements to be removed.
Example:
```
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> mylist = {1, 2, 3, 4, 5, 6};
// Remove element at position 2
mylist.erase(mylist.begin() + 2);
// Remove elements from position 2 to 4
mylist.erase(mylist.begin() + 2, mylist.begin() + 5);
// Print the updated list
for (auto i : mylist)
cout << i << " ";
return 0;
}
```
Output:
```
1 2
```
阅读全文