function template
<algorithm>

std::replace_copy

template <class InputIterator, class OutputIterator, class T>
  OutputIterator replace_copy (InputIterator first, InputIterator last,
                               OutputIterator result,
                               const T& old_value, const T& new_value);
Copy range replacing value
Copies the elements in the range [first,last) to the range beginning at result, replacing the appearances of old_value by new_value.

The function uses operator== to compare the individual elements to old_value.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
10
template <class InputIterator, class OutputIterator, class T>
  OutputIterator replace_copy (InputIterator first, InputIterator last,
                               OutputIterator result, const T& old_value, const T& new_value)
{
  while (first!=last) {
    *result = (*first==old_value)? new_value: *first;
    ++first; ++result;
  }
  return result;
}


Parameters

first, last
Input iterators to the initial and final positions in a sequence. The range copied 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.
result
Output iterator to the initial position of the range where the resulting sequence is stored. The range includes as many elements as [first,last).
The pointed type shall support being assigned a value of type T.
old_value
Value to be replaced.
new_value
Replacement value.

The ranges shall not overlap.

Return value

An iterator pointing to the element that follows the last element written in the result sequence.

Example

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

int main () {
  int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };

  std::vector<int> myvector (8);
  std::replace_copy (myints, myints+8, myvector.begin(), 20, 99);

  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: 10 99 30 30 99 10 10 99

Complexity

Linear in the distance between first and last: Performs a comparison and an assignment for each element.

Data races

The objects in the range [first,last) are accessed.
The objects in the range between result and the returned value are modified.

Exceptions

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

See also