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、元素賦值或迭代器操作丟擲異常,則此函式也丟擲異常。
請注意,無效引數會導致未定義行為

另見