1、partition将区间[first, last)中的元素重新排列。所有被一元条件运算pred判定为true的元素,放在区间的前段,判定为false的元素,放在区间的后段。该算法并不保证元素的原始相对位置。
2、partition源代码
template <class BidirectionalIterator, class Predicate>
BidirectionalIterator partition(BidirectionalIterator first,
BidirectionalIterator last, Predicate pred) {
while (true) {
while (true)
if (first == last)//头指针等于尾指针,所有操作结束
return first;
else if (pred(*first))//头指针所指元素不符合移动条件
++first;
else//头指针所指元素符合移动条件,跳出内循环
break;
--last;//尾指针减1
while (true)
if (first == last)//头指针等于尾指针,所有操作结束
return first;
else if (!pred(*last))//尾指针所指元素不符合移动条件
--last;
else//尾指针所指元素符合移动条件,跳出内循环
break;
iter_swap(first, last);//头尾指针所指元素彼此交换
++first;//头指针前进1,准备下一个外循环迭代
}
}
3、具体例子
#include<iostream>
#include<algorithm>
using namespace std;
template<typename T>
struct isEven:public unary_function<T,bool>{
bool operator()(const T& x) const{
return x % 2 ? false : true;
}
};
int main(){
int ia[] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8 };
partition(begin(ia), end(ia), isEven<int>());
for (int* it = begin(ia); it != end(ia); ++it)
cout << *it << " ";
cout << endl;
system("pause");
return 0;
}
4、上述例子中partition工作过程