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

The replace_copy_if() function is available in the algorithm library in C++. The replace_copy_if() function is used to copy the elements by replacing the specified elements which meet a particular condition.

Syntax

Iterator replace_copy_if (First, Last, Result, Predicate, NewValue);  

Parameter

The replace_copy_if() method takes the following parameters:

  • First: Forward iterator for the initial position of the derived range.
  • Last: Forward iterator for the final position of the derived range.
  • Result: An iterator pointing to the first element of the range, where the elements which met the condition have been stored.
  • Predicate: The unary predicate function that must be satisfied for the element to be replaced.
  • NewValue: Replacement value.

Return

The replace_copy_if() function returns the position after the last copied element in the result vector.

Code

Let’s see the code snippet.

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
bool isEVEN(int x)
{
if (x % 2 == 0)
return 1;
else
return 0;
}
int main()
{
int arr[] = { 10, 11, 12, 13, 14, 15, 100, 200, 300 };
vector<int> v(6);
replace_copy_if(arr + 0, arr + 6, v.begin(), isEVEN, -9);
cout<<"Result vector: "<<endl;
for (int x : v)
cout << x << " ";
cout << endl;
return 0;
}

Explanation

  • In lines 1 to 3, we import the required header files.
  • In lines 8 to 14, we define a function which checks if a number is even.
  • In line 16, we make a main function.
  • In line 18, we initialize an array of int type.
  • In line 19, we declare a vector of int type where the result will be stored.
  • In line 21, we use the replace_copy_if() function to replace all the even numbers with value = -9 using the defined function at line 8.
  • In lines 24 to 26, we display an array and the transformed vector.

Free Resources