C++ Standard Library C++ STL Library

C++ <forward_list> - erase_after() Function



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 example below, the forward_list::erase_after function is used to erase specified element(s) from the flist.

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

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

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

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

  return 0;
}

The output of the above code will be:

flist contains: 10 20 30 40 50 
flist 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 example below:

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

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

  start = flist.begin();
  stop = flist.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
  flist.erase_after(start, stop);

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

  return 0;
}

The output of the above code will be:

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

❮ C++ <forward_list> Library