C++ Standard Library C++ STL Library

C++ <list> - remove_if() Function



The C++ 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);
template <class Predicate>
  void remove_if (Predicate pred);

Parameters

pred Specify an unary predicate that accepts elements of the 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 list::remove_if function is used to delete all elements from the given list which are in the range [20, 30].

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

int main (){
  list<int> MyList{10, 20, 30, 40, 50, 30, 30, 40};
  list<int>::iterator it;

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

  //Remove all elements from the list in range [20, 30]
  MyList.remove_if(del_range);
  
  cout<<"\nMyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

MyList contains: 10 20 30 40 50 30 30 40 
MyList contains: 10 40 50 40 

❮ C++ <list> Library

5