public member function
<list>

std::list::erase

iterator erase (iterator position);iterator erase (iterator first, iterator last);
iterator erase (const_iterator position);iterator erase (const_iterator first, const_iterator last);
Erase elements
Removes from the list container either a single element (position) or a range of elements ([first,last)).

This effectively reduces the container size by the number of elements removed, which are destroyed.

与其他标准序列容器不同,listforward_list容器专门设计用于在任何位置(即使在序列中间)高效地插入和删除元素。

参数

position
Iterator pointing to a single element to be removed from the list.
成员类型iteratorconst_iteratorare bidirectional iterator types that point to elements.
first, last
Iterators specifying a range within the list to be removed[first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
成员类型iteratorconst_iteratorare bidirectional iterator types that point to elements.

返回值

An iterator pointing to the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.

成员类型iterator是指向元素的双向迭代器类型。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// erasing from list
#include <iostream>
#include <list>

int main ()
{
  std::list<int> mylist;
  std::list<int>::iterator it1,it2;

  // set some values:
  for (int i=1; i<10; ++i) mylist.push_back(i*10);

                              // 10 20 30 40 50 60 70 80 90
  it1 = it2 = mylist.begin(); // ^^
  advance (it2,6);            // ^                 ^
  ++it1;                      //    ^              ^

  it1 = mylist.erase (it1);   // 10 30 40 50 60 70 80 90
                              //    ^           ^

  it2 = mylist.erase (it2);   // 10 30 40 50 60 80 90
                              //    ^           ^

  ++it1;                      //       ^        ^
  --it2;                      //       ^     ^

  mylist.erase (it1,it2);     // 10 30 60 80 90
                              //        ^

  std::cout << "mylist contains:";
  for (it1=mylist.begin(); it1!=mylist.end(); ++it1)
    std::cout << ' ' << *it1;
  std::cout << '\n';

  return 0;
}
输出
mylist contains: 10 30 60 80 90


复杂度

Linear in the number of elements erased (destructions).

迭代器有效性

Iterators, pointers and references referring to elements removed by the function are invalidated.
All other iterators, pointers and references keep their validity.

数据竞争

The container is modified.
The elements removed are modified. Concurrently accessing or modifying other elements is safe, although iterating ranges that include the removed elements is not.

异常安全

If position (or the range) is valid, the function never throws exceptions (no-throw guarantee).
否则,将导致未定义行为

另见