C++ Standard Library C++ STL Library

C++ <algorithm> - replace_copy_if() Function



The C++ algorithm::replace_copy_if function is used to copy all elements in the range [first, last) to the range starting at result, with all values replaced by new_value for which pred returns true.

Syntax

template <class InputIterator, class OutputIterator, class UnaryPredicate, class T>
  OutputIterator replace_copy_if (InputIterator first, InputIterator last,
                                  OutputIterator result, UnaryPredicate pred,
                                  const T& new_value);

Parameters

first Specify initial position of the input iterator. The range used is [first,last).
last Specify final position of the input iterator. The range used is [first,last).
result Specify initial position of the output iterator where the result to be stored.
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 replaced with.

Return Value

Returns an iterator pointing to the element that follows the last element replaced in result sequence.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::replace_copy_if function is used to copy all elements of an array to a vector, with all odd elements replaced by 0.

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

int main (){
  int arr[] = {10, 11, 12, 13, 14, 15};
  vector<int> vec(6);
  vector<int>::iterator it;

  //copy elements from array to vector and 
  //replace all odd numbers by 0
  replace_copy_if(arr, arr+6, vec.begin(), isOdd, 0);

  cout<<"arr contains:";
  for(int i = 0; i < 6; ++i)
    cout<<" "<<arr[i];

  cout<<"\nvec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

arr contains: 10 11 12 13 14 15
vec contains: 10 0 12 0 14 0

❮ C++ <algorithm> Library