函式模板
<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);
複製範圍並替換值
該函式將範圍 [first,last) 中的元素複製到以 result 開頭的範圍中,將 old_value 的出現替換為 new_value

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

範圍不應重疊,以免 result 指向範圍 [first,last) 中的某個元素。

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

引數

first, last
輸入迭代器 指向序列的初始位置和結束位置。複製的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
result
輸出迭代器 指向儲存結果序列的範圍的初始位置。該範圍包含的元素數量與 [first,last) 相同。
被指向的型別應支援被賦值為 T 型別的值。
old_value
要被替換的值。
new_value
替換值。

這些範圍不應重疊。

返回值

一個指向結果序列中最後一個寫入元素的下一個元素的迭代器。

示例

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

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


複雜度

線性複雜度,複雜度與 firstlast 之間的距離成正比:對每個元素執行一次比較和一次賦值。

資料競爭

訪問範圍 [first,last) 中的物件。
修改 result 和返回的迭代器之間的範圍內的物件。

異常

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

另見