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

The remove_copy_if() function in C++ helps to copy the elements from a vector or array and remove all the occurrences of the elements that satisfies some condition within that vector or array. This function is available in the <algorithm.h> header file.

Parameters

The remove_copy_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 to where we want to perform the remove operation.

  • result: This is an iterator that points to the start of the new array or vector where we want to store the copied elements. The size of the result should be large enough to accommodate the elements in the range (first, last).

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

Return

The remove_copy_if() function returns an iterator that points to the end of the result where the last element has been copied.

Code

Let’s look at the code 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 };
vector<int> result (9);
remove_copy_if(vec.begin(), vec.end(), result.begin(), IsOdd);
for (int x: result)
cout << x << " ";
return 0;
}

Explanation:

  • From lines 1 to 3, we import the required header files.

  • From lines 6 to 8, we create a unary function that returns true if the number is an odd number. Otherwise, it returns false.

  • In line 12, we create a vector containing integers.

  • In line 13, we create the vector where we want to store the copied data from the vector.

  • In line 15, we call the remove_copy_if() function and pass the required parameters. We are passing the start of result as result.begin() and we want to remove all the occurrences of the element that are odd numbers.

  • In lines 17 and 18, we print the result vector.

Note: You can observe that there are many 0s in the vector, so to avoid this, we can also resize the vector.

This way we can use the remove_copy_if() function in C++.

Free Resources