How to use the replace_copy() function in C++
Overview
In this shot, we will learn how to use the replace_copy() function in C++. This function is available in the <algorithm> library in C++.
The replace_copy() function replaces each element in the range [first, last) that is equal to oldValue with newValue and creates a copy. The function uses the operator ==, meaning double equal to, to compare each of the elements to old_value.
Parameter
The replace_copy() 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: Forward iterator for the initial position of the range where the final result is stored. -
Old value: Replaced value. -
New value: Replacement value.
Return
The replace_copy() function returns the iterator after the last copied element in the destination range.
Syntax
The syntax of the replace_copy() function is shown below:
Iterator replace_copy(first, last, result, oldvalue, newvalue);
Code
Let’s see the code snippet below.
#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(){vector<int> vec = { 33,21,24,21,21 };vector<int> result(vec.size());cout<<"Vector before replace_copy() implementation: ";for (int x : vec)cout << x << " ";cout << endl;replace_copy(vec.begin(), vec.end(), result.begin(), 21, 2000);cout<<"Vector after replace_copy() implementation: ";for (int x : result)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 whether a number is even.
-
In line 16, we make a
mainfunction. -
In line 18, we declare a vector of the
inttype. -
In line 19, we declare our result vector where the copied range will be stored.
-
In line 20, we display the message regarding the original vector.
-
In line 21 to 22, we display the original vector.
-
In line 25, we use the
replace_copy()function to replace all the value = 21 with value = 2000 and display the transformed vector. -
In line 29 to 30, we display the result vector.
This is how we can use the replace_copy() function in C++.