C++ Standard Library C++ STL Library

C++ <algorithm> - replace() Function



The C++ algorithm::replace function is used to assign new_value to all elements in the range [first, last) which are equal to the old_value.

Syntax

template <class ForwardIterator, class T>
  void replace (ForwardIterator first, 
                ForwardIterator last,
                const T& old_value, 
                const T& new_value);  

Parameters

first Specify initial position of the forward iterator. The range used is [first,last).
last Specify final position of the forward iterator. The range used is [first,last).
old_value Specify the value to be replaced.
new_value Specify the value to replace with.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::replace function is used to replace the specified value with a new value in a given range.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main (){
  vector<int> vec{10, 5, 38, 5, 5, 78};
  vector<int>::iterator it;

  cout<<"Before replace call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //replace all 5 with 9 in the vector vec
  replace(vec.begin(), vec.end(), 5, 9);

  cout<<"\nAfter replace call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before replace call, vec contains: 10 5 38 5 5 78
After replace call, vec contains: 10 9 38 9 9 78

❮ C++ <algorithm> Library