partial_sort,partial_sort_copy,nth_element

来源:互联网 发布:华为大数据在贵州 编辑:程序博客网 时间:2024/05/21 06:22

直接代码:

//局部排序  partial_sort partial_sort_copy#include<iostream>#include<string>#include<vector>#include<algorithm>#include<functional>using namespace std;int main(){int a[]={1,4,7,2,5,8,3,6,9,10};vector<int>v(a,a+10);vector<int>vv(a,a+10);vector<int>vvv(10);partial_sort(v.begin(),v.begin()+4,v.end());//部分排序for(vector<int>::iterator itera=v.begin();itera!=v.end();++itera){cout<<*itera<<" ";}cout<<endl;//partial_sort(v.begin(),v.end(),v.end());则部分排序退化为普通排序,但是比sort要慢partial_sort(v.begin()+4,v.end(),v.end(),greater<int>());//前面四个从小到大,后面六个从大到小copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));cout<<endl;partial_sort_copy(vv.begin(),vv.begin()+4,vvv.begin(),vvv.begin()+4);for(vector<int>::iterator it1=vvv.begin();it1!=vvv.begin()+4;++it1){cout<<*it1<<" ";}cout<<endl;partial_sort_copy(vv.begin()+4,vv.end(),vvv.begin()+4,vvv.end(),greater<int>());for(vector<int>::iterator it2=vvv.begin();it2!=vvv.end();++it2){cout<<*it2<<" ";}cout<<endl;system("pause");return 0;}
//nth_element()#include<iostream>#include<algorithm>#include<string>#include<vector>#include<functional>using namespace std;int main(){vector<int>v;for(int i=3;i<8;++i){v.push_back(i);}for(int j=2;j<7;++j){v.push_back(j);}for(int z=1;z<6;++z){v.push_back(z);}nth_element(v.begin(),v.begin()+3,v.end());cout<<"the four lowest elements are:";//前四个最小的copy(v.begin(),v.begin()+4,ostream_iterator<int>(cout," "));cout<<endl;nth_element(v.begin(),v.end()-4,v.end());cout<<"the four highest elements are:";//后四个最大的copy(v.end()-4,v.end(),ostream_iterator<int>(cout," "));cout<<endl;nth_element(v.begin(),v.begin()+3,v.end(),greater<int>());cout<<"the four highest elements are:";//前四个最大的copy(v.begin(),v.begin()+4,ostream_iterator<int>(cout," "));cout<<endl;system("pause");return 0;}


 

原创粉丝点击