C++ Standard Library C++ STL Library

C++ <forward_list> - remove_if() Function



The C++ forward_list::remove_if function is used to delete all elements for which Predicate pred returns true.

Syntax

template <class Predicate>
  void remove_if (Predicate pred);

Parameters

pred Specify an unary predicate that accepts elements of the forward_list as argument, and returns true for the values to be removed, false otherwise.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the forward_list::remove_if function is used to delete all elements from the given forward_list which are in the range [20, 30].

#include <iostream>
#include <forward_list>
using namespace std;
 
//a predicate implemented as a function
bool del_range (int i) {return (i>=20 && i<=30);}

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 elements from the forward_list in range [20, 30]
  flist.remove_if(del_range);
  
  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 40 50 40 

❮ C++ <forward_list> Library