STL 之 partition()方法 和 stable_partition()方法

转自:https://blog.csdn.net/godenlove007/article/details/7982307

这两个方法都用来将指定容器的元素根据指定的predicate函数分成两个子序列,其中满足predicate()函数的,返回值为true的作为第一个序列[v.begin(), bound), 而[bound, v.end())的作为第二个序列。两个方法的区别在于, partition()对于两个子序列中的元素并不排序,而stable_partition()则对两个子序列的元素也进行排序。

BidirectionalIterator partition ( BidirectionalIterator first, BidirectionalIterator last, Predicate pred );
BidirectionalIterator stable_partition ( BidirectionalIterator first, BidirectionalIterator last, Predicate pred );
Parameters:
first, last 第一个和第二个参数说明给定源容器的范围 [first, last)
pred 第三个参数给定进行分组的规则函数 布尔型返回值 对于返回true的所有元素作为第一个子序列,对于返回false的所有元素作为第二个子序列
Return value 返回值是 指向第二个子序列的首元素迭代器

#include 
 #include 
 #include 
 
 using namespace std;
 
 bool IsOdd(int i)
 {
     return (i%2 == 1);
 }
 
 int main()
 {
     vector v = {2,6,3,8,4,5,9,7,1,0};
 
     cout<<"The original elements in the vector are: "<::iterator it, bound;
 
     for(it = v.begin(); it != v.end(); it++)
         cout<<*it<<" ";
     cout<

输出:

The original elements in the vector are:
2 6 3 8 4 5 9 7 1 0
First use the function partition() to separate all elements into 2 groups without ordering:
All odd elements in the vector are:
1 7 3 9 5
All even elements in the vector are:
4 8 6 2 0
Secondly use the function stable_partition() to separate all elements into 2 groups with ordering:
All odd elements in the vector are:
3 5 9 7 1
All even elements in the vector are:
2 6 8 4 0

可以看到,stable函数可以保证在分类过程中不改变原来同一类元素的相对位置。

你可能感兴趣的:(STL 之 partition()方法 和 stable_partition()方法)