C++ STL实现sort

9 篇文章 0 订阅

sort

#include <iostream>
#include <algorithm>
using namespace std;


template<typename T>
void mswap(T& t1,T& t2){
	T t = t1;
	t1 = t2;
	t2 = t;
}

template<typename T>
void msort(T elems[],size_t cnt){
	for(int i=0;i<cnt;i++){
		bool isswap = false;
		for(int j=1;j<cnt-i;j++){
			if(elems[j] < elems[j-1]){//改变这个  就能改变排序规则
				mswap(elems[j],elems[j-1]);		
				isswap = true;
			}	
		}	
		if(!isswap){
			break;	
		}
	}
}

template<typename T>
void print(T elems[],size_t cnt){
	for(int i=0;i<cnt;i++)
		cout << elems[i] << " ";
	cout << endl;
}

class Stu{
private:
	int no;
	string name;
	int s;
public:
	Stu(int no,string name,int s):no(no),name(name),s(s){}
	int getNo()const{
		return no;	
	}
	int getS()const{
		return s;	
	}
	friend ostream& operator<<(ostream& os,const Stu& s);
};

ostream& operator<<(ostream& os,const Stu& s){
	return os << s.no << " " << s.name << " " << s.s << endl;	
}
//对象  函数对象
class Comp{
public:	
	bool operator()(const Stu& s1,const Stu& s2){
		return s2.getS() < s1.getS();
	}
};

int main(){
	int arr[9] = {7,2,9,8,1,4,5,0,6};
	msort(arr,9);
	print(arr,9);
	Stu srr[5] = {Stu(110,"jack",90),Stu(120,"lily",97),
		Stu(119,"lucy",89),Stu(127,"james",99),Stu(133,"jordan",97)};
	sort(srr,srr+5,Comp());//匿名对象   匿名函数对象
	print(srr,5);
	return 0;	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HOVL_C++

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值