partial_sort,partial_sort_copy,nth_element

97 篇文章 0 订阅
92 篇文章 0 订阅

直接代码:

//局部排序  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;
}


 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值