C++ Standard Library C++ STL Library

C++ <algorithm> - remove_if() Function



The C++ algorithm::remove_if function is used to remove the elements in the range [first, last) for which pred returns true. This transforms the range [first, last) into range containing no element for which pred returns true and returns iterator to the new end of the range. Please note that, the function cannot alter the size of the container. The removal is done by swapping the element with the next element for which pred returns false.

Syntax

template <class ForwardIterator, class UnaryPredicate>
  ForwardIterator remove_if (ForwardIterator first, 
                             ForwardIterator last,
                             UnaryPredicate pred);

Parameters

first Specify initial position of the forward iterator. The range used is [first,last).
last Specify final position of the forward iterator. The range used is [first,last).
pred Specify an unary function that accepts an element in the range as argument, and returns a value convertible to bool. The element will be removed if the function returns true.

Return Value

Returns an iterator to the element that follows the last element not removed.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::remove_if function is used to remove all negative elements from the given vector.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std; 

bool isNegative (int i) {
  return (i < 0) ;
}

int main (){
  vector<int> vec{10, -20, 30, -10, -60, 20, 50};
  vector<int>::iterator it;

  cout<<"Before remove_if call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //remove all negative elements
  auto newend = remove_if(vec.begin(), vec.end(), isNegative);

  cout<<"\nAfter remove_if call, vec contains:";
  for(it = vec.begin(); it != newend; ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before remove_if call, vec contains: 10 -20 30 -10 -60 20 50
After remove_if call, vec contains: 10 30 20 50

❮ C++ <algorithm> Library

5