public member function

std::forward_list::erase_after

<forward_list>
iterator erase ( const_iterator position );
iterator erase ( const_iterator position, const_iterator last );
Erase elements
Removes from the forward_list container either a single element (the one after position) or a range of elements ((position,last)).

This effectively reduces the container size by the number of elements removed, calling their destructors.

Unlike other standard sequence containers, list and forward_list objects are specifically designed to be efficient inserting and removing elements in any position, even in the middle of the sequence.

Parameters

position
Iterator pointing to an element in the forward_list container. The (first) element removed is the one after this.
Member type const_iterator is a forward iterator type.
last
Iterator pointing to the element after the last one to be removed. The range of elements removed is the open interval (position,last), which includes all the elements between position and last, but not position nor last themselves.
Member type const_iterator is a forward iterator type.

Return value

An iterator pointing to the element that follows the last element erased by the function call, which is last for the second version.
If the operation erased the last element in the sequence, the value returned is end.

Member type iterator is a forward iterator type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// erasing from forward_list
#include <iostream>
#include <forward_list>

int main ()
{
  std::forward_list<int> mylist = {10, 20, 30, 40, 50};

                                            // 10 20 30 40 50
  auto it = mylist.begin();                 // ^

  it = mylist.erase_after(it);              // 10 30 40 50
                                            //    ^
  it = mylist.erase_after(it,mylist.end()); // 10 30
                                            //       ^

  std::cout << "mylist contains:";
  for (int& x: mylist) std::cout << " " << x;
  std::cout << std::endl;

  return 0;
}

Output:
mylist contains: 10 30

Complexity

Linear on the number of elements erased (destructors).

Iterator validity

All the iterators, pointers and references to elements that have not been removed remain valid after this operation and refer to the same elements they were referring to before.

See also