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


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 below example, 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> f_List{10, 20, 30, 40, 50, 30, 30, 40};
  forward_list<int>::iterator it;

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

  //Remove all elements from the forward_list in range [20, 30]
  f_List.remove_if(del_range);
  
  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 30 30 40 
f_List contains: 10 40 50 40 

❮ C++ - Forward List