How to use the remove_if() function in C++

The remove_if() function in C++ helps to remove all the occurrences of the values within a specified range that satisfies some condition. This function is available in the <algorithm.h> header file.

Parameters

The remove_if() function accepts the following parameters:

  • first: This is an iterator that points to the first index of the array or vector from where we want to perform the remove operation.

  • last: This is an iterator that points to the last index of the array or vector till where we want to perform the remove operation.

  • condition: This is an unary function that accepts one element and returns a boolean value indicating whether the condition is satisfied or not.

Return

The remove_if() function returns an iterator that points to past the last element that is not removed.

Example

Let’s look at the example below:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool IsOdd(int a){
return (a % 2 == 1);
}
int main () {
vector<int> vec = { 1, 2, 3, 4, 3, 6, 7, 3, 10 };
auto it = remove_if(vec.begin(), vec.end(), IsOdd);
for (auto i = vec.begin(); i != it; i++)
cout << *i << " ";
return 0;
}

Explanation

  • In lines 1 to 3 we import the required libraries.
  • In lines 6 and 7 we define the unary function that returns true if the number is odd, otherwise it returns false.
  • In line 12 we create a vector containing integer values.
  • In line 13 we call the remove_if() function and pass the unary function as the condition to remove all the odd numbers from the vector.
  • In lines 11 and 12 we print the vector values after removing all the odd numbers from it. The remove() function returns an iterator that points to past-the-last element not removed and hence we need to run the loop till that iterator only.

This way we can easily remove all the occurrences of the values from a vector within the specified range which satisfies the condition.

Free Resources