C++ Standard Library C++ STL Library

C++ <forward_list> - remove() Function



The C++ forward_list::remove function is used to delete all occurrences of specified element from the forward_list container.

Syntax

void remove (const value_type& val);

Parameters

val Specify the value of the element which need to be removed from the forward_list.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the forward_list::remove function is used to delete all occurrences of specified element from the list called flist.

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

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

  //Remove all occurrences of 30 from flist
  flist.remove(30);
  
  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 30 30 40 
flist contains: 10 20 40 50 40 

❮ C++ <forward_list> Library

5