Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ forward_list::erase_after function is used to erase an element or a range of elements from the forward_list. Each deletion operation reduces the size of the container by the number of elements erased from the container.

Syntax

//deletes single element (the one after the position)
iterator erase_after (const_iterator position);

//deletes a range of elements (all elements in open interval (position, last))
iterator erase_after (const_iterator position, const_iterator last);

Parameters

position Iterator pointing to the element before the first element to be removed.
last Iterator pointing to the element after the last element to be removed.

Return Value

An iterator that follows the last element erased from the container. If the operation erases last element of the container, it returns past-the-last element.

Time Complexity

Linear i.e, Θ(n).

Example: erase a single element

In the below example, the forward_list::erase_after function is used to erase specified element(s) from the f_list.

#include <iostream>
#include <forward_list>
using namespace std;
 
int main (){
  forward_list<int> f_list{10, 20, 30, 40, 50};
  forward_list<int>::iterator it;

  cout<<"f_list contains: ";
  for(it = f_list.begin(); it != f_list.end(); it++)
    cout<<*it<<" "; 

  it = f_list.begin();
  //advance the iterator to the position = 2
  advance(it, 1);
  //erase element at position = 3
  f_list.erase_after(it);

  cout<<"\nf_list contains: ";
  for(it = f_list.begin(); it != f_list.end(); it++)
    cout<<*it<<" ";   

  return 0;
}

The output of the above code will be:

f_list contains: 10 20 30 40 50 
f_list contains: 10 20 40 50 

Example: erase a range of elements

Similarly, a range of elements can be erased from the forward list. Consider the below example:

#include <iostream>
#include <forward_list>
using namespace std;
 
int main (){
  forward_list<int> f_list{10, 20, 30, 40, 50, 60, 70};
  forward_list<int>::iterator it;
  forward_list<int>::iterator start;
  forward_list<int>::iterator stop;

  cout<<"f_list contains: ";
  for(it = f_list.begin(); it != f_list.end(); it++)
    cout<<*it<<" "; 

  start = f_list.begin();
  stop = f_list.begin();
  //advance the start iterator to the position = 2
  advance(start, 1); 
  //advance the stop iterator to the position = 6
  advance(stop, 5);    
  //erase element from position = 3 to position = 5
  f_list.erase_after(start, stop);

  cout<<"\nf_list contains: ";
  for(it = f_list.begin(); it != f_list.end(); it++)
    cout<<*it<<" ";   

  return 0;
}

The output of the above code will be:

f_list contains: 10 20 30 40 50 60 70 
f_list contains: 10 20 60 70 

❮ C++ - Forward List