function template
<algorithm>

std::replace_copy_if

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);
Copy range replacing value
Copies the elements in the range [first,last) to the range beginning at result, replacing those for which pred returns true by new_value.

此函数模板的行为等同于
1
2
3
4
5
6
7
8
9
10
11
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)
{
  while (first!=last) {
    *result = (pred(*first))? new_value: *first;
    ++first; ++result;
  }
  return result;
}

参数

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.
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 in the copy (if true, it is replaced).
该函数不得修改其参数。
This can either be a function pointer or a function object.
new_value
Value to assign to replaced values.

这些范围不应重叠。

返回值

一个指向结果序列中最后一个写入元素的下一个元素的迭代器。

示例

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

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

int main () {
  std::vector<int> foo,bar;

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

  bar.resize(foo.size());   // allocate space
  std::replace_copy_if (foo.begin(), foo.end(), bar.begin(), IsOdd, 0);
                                                        // 0 2 0 4 0 6 0 8 0

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

  return 0;
}

输出
second contains: 0 2 0 4 0 6 0 8 0


复杂度

Linear in the distance between first and last: Applies pred and performs an assignment for each element.

数据竞争

访问范围 [first,last) 中的对象。
修改 result 和返回的迭代器之间的范围内的对象。

异常

如果 pred、元素赋值或迭代器操作抛出异常,则此函数也抛出异常。
请注意,无效参数会导致未定义行为

另见