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 );
在範圍內替換值
對於使得 pred 返回 true 的範圍 [first,last) 中的所有元素,將 new_value 賦給它們。

此函式模板的行為等同於
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;
  }
}

引數

first, last
Forward iterators 指向支援被賦值為 T 型別值的元素序列的初始和末尾位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
pred
一元函式,接受範圍內的元素作為引數,並返回一個可轉換為 bool 的值。返回的值指示元素是否應該被替換(如果為 true,則會被替換)。
該函式不得修改其引數。
這可以是函式指標或函式物件。
new_value
要賦給被替換元素的值。

返回值



示例

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;
}

輸出
myvector contains: 0 2 0 4 0 6 0 8 0


複雜度

線性與 firstlast 之間的 距離 成正比:將 pred 應用於每個元素,並將值賦給匹配的元素。

資料競爭

範圍 [first,last) 中的物件被訪問並可能被修改。

異常

如果 pred、元素賦值或迭代器操作丟擲異常,則此函式也丟擲異常。
請注意,無效引數會導致 未定義行為

另見