函式模板
<algorithm>

std::replace

template <class ForwardIterator, class T>  void replace (ForwardIterator first, ForwardIterator last,                const T& old_value, const T& new_value);
範圍內的替換值
將範圍 [first,last) 中與 old_value 相等的元素全部賦值為 new_value

該函式使用 operator== 將各個元素與 old_value 進行比較。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value)
{
  while (first!=last) {
    if (*first == old_value) *first=new_value;
    ++first;
  }
}

引數

first, last
前向迭代器 指向一個元素序列的初始和末尾位置,這些元素支援比較並能被賦值為 T 型別的值。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
old_value
要被替換的值。
new_value
替換值。

返回值



示例

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

int main () {
  int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
  std::vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20

  std::replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 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;
}

輸出
myvector contains: 10 99 30 30 99 10 10 99


複雜度

線性時間複雜度,複雜度與 firstlast 之間的 距離 成正比:比較每個元素並將值賦給匹配的元素。

資料競爭

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

異常

如果任何元素比較、元素賦值或迭代器操作丟擲異常,則丟擲異常。
請注意,無效引數會導致未定義行為

另見