标签:rate isod begin names 输出 cout last algorithm 序列
转自: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 <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool IsOdd(int i)
{
return (i%2 == 1);
}
int main()
{
vector<int> v = {2,6,3,8,4,5,9,7,1,0};
cout<<"The original elements in the vector are: "<<endl;
vector<int>::iterator it, bound;
for(it = v.begin(); it != v.end(); it++)
cout<<*it<<" ";
cout<<endl;
cout<<"First use the function partition() to separate all elements into 2 groups without ordering: "<<endl;
//use partition to separate the vector into 2 parts...
bound = partition(v.begin(), v.end(), IsOdd);
cout << "All odd elements in the vector are:" <<endl;
for(it = v.begin(); it != bound; it++)
cout<<*it<<" ";
cout<<endl;
cout<< "All even elements in the vector are:" <<endl;
for(it = bound; it != v.end(); it++)
cout<<*it<<" ";
cout<<endl;
v.clear();
for(int i = 0; i < 10; i++)
v.push_back(i);
cout<<"Secondly use the function stable_partition() to separate all elements into 2 groups with ordering: "<<endl;
//use stable_partition to separate the vector into 2 parts...
bound = stable_partition(v.begin(), v.end(), IsOdd);
cout << "All odd elements in the vector are:" <<endl;
for(it = v.begin(); it != bound; it++)
cout<<*it<<" ";
cout<<endl;
cout<< "All even elements in the vector are:" <<endl;
for(it = bound; it != v.end(); it++)
cout<<*it<<" ";
cout<<endl;
return 0;
}
输出:
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()方法
标签:rate isod begin names 输出 cout last algorithm 序列
原文地址:https://www.cnblogs.com/xym4869/p/12249826.html