Replaces elements that match a criterion with another value

You're viewing an older version of this page (#4136). View the current version.

View versions (1)

Definition

The replace_if() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class ForwardIterator, class Predicate, class Type >
   void replace_if(
      ForwardIterator first, 
      ForwardIterator last,
      Predicate pred, 
      const Type& val
   );

Parameters:

ParameterDescription
firstA forward iterator pointing to the position of the first element in the range from which elements are being replaced
lastAn iterator pointing to the position one past the final element in the range from which elements are being replaced
predThe unary predicate that must be satisfied is the value of an element is to be replaced
valThe new value being assigned to the elements whose old value satisfies the predicate

Description

Replace_if function does the same thing that the http://codecogs.com/reference/computing/stl/algorithms/modifying/replace.php"replace" function but uses the pred predicate instead of operator==.

Return Value

None.

Complexity

The complexity is linear; there are last - first applications of pred and at most last - first assignments.

References

Example 1
Problem

This program illustrates the use of the STL replace_if() algorithm to replace all copies of a given value in a vector of integers that satisfy a given predicate with another value.

Workings
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/* Determines if an integer is divisible by 3.
 n contains an integer.
 Returns true if n is divisible by 3, and otherwise false.
*/

bool isDivisibleByThree
(
  int n //in
)
{
  return (n%3 == 0);
}

int main()
{
  int a[] = {1, 2, 2, 3, 4, 5, 2, 6};
  vector<int> v(a, a+8);

  cout <<"\nHere are the values in the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  cout <<"\nNow we replace all values divisble by 3 with 123.";
  replace_if(v.begin(), v.end(), isDivisibleByThree, 123);

  cout <<"\nHere are the revised contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  return 0;
}
Solution

Output:

Here are the values in the vector:
1 2 2 3 4 5 2 6

Now we replace all values divisble by 3 with 123.

Here are the revised contents of the vector:
1 2 2 123 4 5 2 123