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.
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.
The remove_if() function returns an iterator that points to past the last element that is not removed.
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;}
true if the number is odd, otherwise it returns false.remove_if() function and pass the unary function as the condition to remove all the odd numbers from the vector.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.