I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com

replace_if

Replaces elements that match a criterion with another value
+ View version details

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:
Parameter Description
first A forward iterator pointing to the position of the first element in the range from which elements are being replaced
last An iterator pointing to the position one past the final element in the range from which elements are being replaced
pred The unary predicate that must be satisfied is the value of an element is to be replaced
val The new value being assigned to the elements whose old value satisfies the predicate

Description

Replace_if function does the same thing that the 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.
Example:

Example - replace_if algorithm
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
References