function template
<algorithm>

std::replace_if

template <class ForwardIterator, class UnaryPredicate, class T>  void replace_if (ForwardIterator first, ForwardIterator last,                   UnaryPredicate pred, const T& new_value );
Replace values in range
Assigns new_value to all the elements in the range [first,last) for which pred returns true.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
template < class ForwardIterator, class UnaryPredicate, class T >
  void replace_if (ForwardIterator first, ForwardIterator last,
                   UnaryPredicate pred, const T& new_value)
{
  while (first!=last) {
    if (pred(*first)) *first=new_value;
    ++first;
  }
}

Parameters

first, last
Forward iterators to the initial and final positions in a sequence of elements that support being assigned a value of type T. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
pred
Unary function that accepts an element in the range as argument, and returns a value convertible to bool. The value returned indicates whether the element is to be replaced (if true, it is replaced).
The function shall not modify its argument.
This can either be a function pointer or a function object.
new_value
Value to assign to replaced elements.

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// replace_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> myvector;

  // set some values:
  for (int i=1; i<10; i++) myvector.push_back(i);               // 1 2 3 4 5 6 7 8 9

  std::replace_if (myvector.begin(), myvector.end(), IsOdd, 0); // 0 2 0 4 0 6 0 8 0

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Output:
myvector contains: 0 2 0 4 0 6 0 8 0


Complexity

Linear in the distance between first and last: Applies pred to each element and assigns to those matching.

Data races

The objects in the range [first,last) are accessed and potentially modified.

Exceptions

Throws if any of pred, the element assignments or the operations on iterators throws.
Note that invalid arguments cause undefined behavior.

See also