In this shot, we will discuss how to use the replace()
function in C++.
The replace()
function replaces each element in the range [first, last) that is equal to oldValue
with newValue
. The function uses operator ==
to compare each of the elements to oldValue
.
First
: Forward iterator for the initial position of the derived range.Last
: Forward iterator for the final position of the derived range.OldValue
: Replaced value.NewValue
: Replacement value.The replace()
function does not return anything.
The syntax of the replace()
function is shown below:
void replace(first, last, oldvalue, newvalue);
Let’s look at the code snippet below.
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){vector<int> vec = {3, 1, 2, 1, 2, 1, 5, 6, 12, 5};cout<<"The vector before calling replace(): ";for(int x: vec)cout << x << " ";cout << endl;replace(vec.begin(), vec.end(), 1, 100);cout<<"The vector after calling replace(): ";for(int x: vec)cout << x << " ";return 0;}
main
function.replace()
function to replace 1
in the vector with the value 100
.In this way, we can use the replace()
function to replace the elements present inside containers in C++.