partition算法作用為對指定范圍內元素重新排序,使用輸入的函數,把結果為true的元素放在結果為false的元素之前
stable_partition算法:與partition類似,不過不保證保留容器中的相對順序
C++ partition()函數
partition() 和stable_partition函數定義於<algorithm>頭文件中,因此需要引入頭文件#include <algorithm>
格式:
ForwardIterator partition (ForwardIterator first,
ForwardIterator last,
UnaryPredicate pred);
其中,first 和 last 為正向迭代器,其組合 [first, last) 用於指定該函數的作用范圍;pred 用於指定篩選規則。(篩選規則,其本質就是一個可接收 1 個參數且返回值類型為 bool 的函數,可以是普通函數,也可以是一個函數對象。)
同時,partition() 函數還會返回一個正向迭代器,其指向的是兩部分數據的分界位置,更確切地說,指向的是第二組數據中的第 1 個元素。
#include <iostream> #include <algorithm> #include <vector> using namespace std; //以普通函數的方式定義partition()函數的篩選規則 bool cmp(int i) { return (i % 2) == 0; } //以函數對象的形式定義篩選規則 class cmp2{ public: bool operator()(const int& i) { return (i%2 == 0); } }; int main() { vector<int> myvector; for(int i=1;i<10;i++){ myvector.push_back(i); } vector<int>::iterator bound; //以 mycomp2 規則,對 myvector 容器中的數據進行分組 bound = std::partition(myvector.begin(), myvector.end(), cmp2()); for (vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it) { cout << *it << " "; } cout << "\nbound = " << *bound; return 0; }
運行結果:

C++ stable_partition()函數
partition() 函數只負責對指定區域內的數據進行分組,並不保證各組中元素的相對位置不發生改變。而如果想在分組的同時保證不改變各組中元素的相對位置,可以使用 stable_partition() 函數。
stable_partition() 函數可以保證對指定區域內數據完成分組的同時,不改變各組內元素的相對位置。
格式:
BidirectionalIterator stable_partition (BidirectionalIterator first,
BidirectionalIterator last,
UnaryPredicate pred);
舉例:
#include <iostream> #include <algorithm> #include <vector> using namespace std; //以普通函數的方式定義partition()函數的篩選規則 bool cmp(int i) { return (i % 2) == 0; } //以函數對象的形式定義篩選規則 class cmp2{ public: bool operator()(const int& i) { return (i%2 == 0); } }; int main() { vector<int> myvector; for(int i=1;i<10;i++){ myvector.push_back(i); } vector<int>::iterator bound; //以 mycomp2 規則,對 myvector 容器中的數據進行分組 bound = std::stable_partition(myvector.begin(), myvector.end(), cmp2()); for (vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it) { cout << *it << " "; } cout << "\nbound = " << *bound; return 0; }

