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

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.

Parameters

  • 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.

Return value

The replace() function does not return anything.

Syntax

The syntax of the replace() function is shown below:

void replace(first, last, oldvalue, newvalue);

Code

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;
}

Explanation

  • In lines 1 to 3, we imported the required header files.
  • In line 6, we made the main function.
  • In line 8, we initialized a vector containing some integer values.
  • In lines 10 and 11, we printed the elements of the original vector.
  • In line 14, we used the replace() function to replace 1 in the vector with the value 100.
  • In lines 16 and 17, we printed the vector after replacement.

In this way, we can use the replace() function to replace the elements present inside containers in C++.

Free Resources