函式模板
<algorithm>

std::partition_copy

template <class InputIterator, class OutputIterator1,          class OutputIterator2, class UnaryPredicate pred>  pair<OutputIterator1,OutputIterator2>    partition_copy (InputIterator first, InputIterator last,                    OutputIterator1 result_true, OutputIterator2 result_false,                    UnaryPredicate pred);
將範圍劃分為兩部分
將範圍 [first,last)pred 返回 true 的元素複製到 result_true 指向的範圍,將 pred 返回 false 的元素複製到 result_false 指向的範圍。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template <class InputIterator, class OutputIterator1,
          class OutputIterator2, class UnaryPredicate pred>
  pair<OutputIterator1,OutputIterator2>
    partition_copy (InputIterator first, InputIterator last,
                    OutputIterator1 result_true, OutputIterator2 result_false,
                    UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) {
      *result_true = *first;
      ++result_true;
    }
    else {
      *result_false = *first;
      ++result_false;
    }
    ++first;
  }
  return std::make_pair (result_true,result_false);
}

引數

first, last
輸入迭代器,指向待複製分割槽的範圍的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
result_true
輸出迭代器,指向儲存 pred 返回 true 的元素的範圍的起始位置。
result_false
輸出迭代器,指向儲存 pred 返回 false 的元素的範圍的起始位置。
pred
一元函式,接受 InputIterator 指向的元素作為引數,並返回可轉換為 bool 的值。返回值指示該元素應複製到哪個結果範圍。
該函式不得修改其引數。
可以是函式指標,也可以是函式物件。

這些範圍不應重疊。
Output iterator 型別指向的物件應支援被賦值範圍 [first,last) 中元素的值。

返回值

一個 pair,其迭代器分別指向 result_trueresult_false 生成的序列的末尾。

其成員 first 指向 pred 返回 true 的元素序列中最後一個元素之後的位置。
其成員 second 指向 pred 返回 false 的元素序列中最後一個元素之後的位置。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// partition_copy example
#include <iostream>     // std::cout
#include <algorithm>    // std::partition_copy, std::count_if
#include <vector>       // std::vector

bool IsOdd (int i) { return (i%2)==1; }

int main () {
  std::vector<int> foo {1,2,3,4,5,6,7,8,9};
  std::vector<int> odd, even;

  // resize vectors to proper size:
  unsigned n = std::count_if (foo.begin(), foo.end(), IsOdd);
  odd.resize(n); even.resize(foo.size()-n);

  // partition:
  std::partition_copy (foo.begin(), foo.end(), odd.begin(), even.begin(), IsOdd);

  // print contents:
  std::cout << "odd: ";  for (int& x:odd)  std::cout << ' ' << x; std::cout << '\n';
  std::cout << "even: "; for (int& x:even) std::cout << ' ' << x; std::cout << '\n';

  return 0;
}

輸出
odd: 1 3 5 7 9
even: 2 4 6 8


複雜度

線性複雜度,複雜度為 firstlast 之間 距離的線性複雜度:呼叫 pred 併為每個元素執行一次賦值。

資料競爭

範圍 [first,last) 中的物件被訪問(每個訪問一次)。
result_trueresult_false 所指向的範圍中的物件,直到迭代器指向的元素之前的部分會被修改(每個修改一次)。

異常

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

另見