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.
Iterator replace_copy_if (First, Last, Result, Predicate, NewValue);
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.The replace_copy_if()
function returns the position after the last copied element in the result vector.
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;elsereturn 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;}
main
function.int
type.int
type where the result will be stored.replace_copy_if()
function to replace all the even numbers with value = -9 using the defined function at line 8.