函式模板
<algorithm>

std::copy_if

template <class InputIterator, class OutputIterator, class UnaryPredicate>  OutputIterator copy_if (InputIterator first, InputIterator last,                          OutputIterator result, UnaryPredicate pred);
複製範圍中的特定元素
將範圍 [first,last)pred 返回 true 的元素複製到以 result 開頭的範圍。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
13
template <class InputIterator, class OutputIterator, class UnaryPredicate>
  OutputIterator copy_if (InputIterator first, InputIterator last,
                          OutputIterator result, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) {
      *result = *first;
      ++result;
    }
    ++first;
  }
  return result;
}

引數

first, last
指向序列中起始和結束位置的輸入迭代器。複製的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
InputIterator 應指向一個可以 賦值OutputIterator 指向的元素型別。
result
輸出迭代器,指向儲存結果序列的範圍的起始位置。該範圍包含與 [first,last) 一樣多的元素。
pred
一元函式,接受範圍中的元素作為引數,並返回一個可轉換為 bool 的值。返回值表示該元素是否應被複制(如果為 true,則複製)。
該函式不得修改其任何引數。
這可以是函式指標,也可以是函式物件。

這些範圍不應重疊。

返回值

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

示例

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

int main () {
  std::vector<int> foo = {25,15,5,-5,-15};
  std::vector<int> bar (foo.size());

  // copy only positive numbers:
  auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
  bar.resize(std::distance(bar.begin(),it));  // shrink container to new size

  std::cout << "bar contains:";
  for (int& x: bar) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

輸出
bar contains: 25 15 5


複雜度

線性於 firstlast 之間的 距離:將 pred 應用於範圍中的每個元素,並執行最多與該距離等量的賦值操作。

資料競爭

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

異常

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

另見