函式模板
<algorithm>

std::partition

template <class BidirectionalIterator, class UnaryPredicate>  BidirectionalIterator partition (BidirectionalIterator first,                                   BidirectionalIterator last, UnaryPredicate pred);
template <class ForwardIterator, class UnaryPredicate>  ForwardIterator partition (ForwardIterator first,                             ForwardIterator last, UnaryPredicate pred);
對範圍進行分割槽
重新排列範圍 [first,last) 中的元素,使得所有 pred 返回 true 的元素都位於 pred 返回 false 的元素之前。返回的迭代器指向第二個組的第一個元素。

各組內的相對順序不一定與呼叫前相同。有關具有類似行為但各組內順序穩定的函式,請參閱 stable_partition

此函式模板(C++98)的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <class BidirectionalIterator, class UnaryPredicate>
  BidirectionalIterator partition (BidirectionalIterator first,
                                   BidirectionalIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    while (pred(*first)) {
      ++first;
      if (first==last) return first;
    }
    do {
      --last;
      if (first==last) return first;
    } while (!pred(*last));
    swap (*first,*last);
    ++first;
  }
  return first;
}

引數

first, last
雙向迭代器指向要分割槽的序列的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast1 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
前向迭代器指向要分割槽的序列的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
ForwardIterator 應指向一個 swap 已定義且能交換其引數值的型別。
pred
一元函式,它接受範圍內的元素作為引數,並返回一個可轉換為 bool 的值。返回值指示元素是否應放在前面(如果為 true,則該元素放在所有 pred 返回 false 的元素之前)。
該函式不得修改其引數。
這可以是函式指標,也可以是函式物件。

返回值

指向第二個元素組(pred 返回 false 的元素)的第一個元素的迭代器,如果該組為空,則為 last

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// partition algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::partition
#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::vector<int>::iterator bound;
  bound = std::partition (myvector.begin(), myvector.end(), IsOdd);

  // print out content:
  std::cout << "odd elements:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=bound; ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  std::cout << "even elements:";
  for (std::vector<int>::iterator it=bound; it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

可能的輸出
odd elements: 1 9 3 7 5
even elements: 6 4 8 2


複雜度

線性複雜度,複雜度為 firstlast 之間 距離的線性複雜度:對每個元素應用 pred,並可能交換其中一些元素(如果迭代器型別是 雙向的,則交換次數最多為該距離的一半,否則最多為該距離)。

資料競爭

範圍[first,last)內的物件將被修改。

異常

如果元素交換或迭代器操作引發異常,則丟擲異常。
請注意,無效引數會導致未定義行為

另見