public member function
<forward_list>

std::forward_list::erase_after

iterator erase_after (const_iterator position);
iterator erase_after (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, which are destroyed.

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 that points to elements.
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 that points to elements.

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 that points to elements.

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 << '\n';

  return 0;
}

Output:
mylist contains: 10 30

Complexity

Linear in the number of elements erased (destructions).

Iterator validity

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

Data races

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.

Exception safety

If position (or the range) is valid, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.

See also