C++ Standard Library C++ STL Library

C++ <algorithm> - replace_if() Function



The C++ algorithm::replace_if function is used to assign new_value to all elements in the range [first, last) for which the unary function pred returns true.

Syntax

template <class ForwardIterator, class UnaryPredicate, class T>
  void replace_if (ForwardIterator first, 
                   ForwardIterator last,
                   UnaryPredicate pred, 
                   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).
pred Specify an unary function that accepts an element in the range as argument, and returns a value convertible to bool. The element will be replaced if the function returns true.
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_if function is used to replace all elements in a given vector based on specified condition.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
bool isEven (int i) {return (i%2==0);}

int main (){
  vector<int> vec{11, 12, 13, 14, 15, 16};
  vector<int>::iterator it;

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

  //replace all even numbers with 0
  replace_if(vec.begin(), vec.end(), isEven, 0);

  cout<<"\nAfter replace_if 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_if call, vec contains: 11 12 13 14 15 16
After replace_if call, vec contains: 11 0 13 0 15 0

❮ C++ <algorithm> Library