C++模板编程-sort函数笔记

#include <iostream>
#include <vector> 
#include <algorithm>

using namespace std;

class Person
{
public:
	string name;
	int age;
	int height;
	Person(string name , int age , int height)
	{
		this->name = name;
		this->age = age;
		this->height = height;
	}	
	friend ostream& operator << (ostream &os , Person &p);
}; 
ostream& operator << (ostream &os , Person &p)
{
	cout<<"姓名:"<<p.name<<" 年龄:"<<p.age<<" 身高:"<<p.height<<endl;
	return os; 
}

bool comperson(Person &p1 , Person &p2)
{
	//p1.xx < p2.xx 按xx从小到大顺序排序
	//p1.xx > p2.xx 按xx从大到小顺序排序
	
	if(p1.height == p2.height)
	{
		return p1.age > p2.age;
	} 
	else
	{
		return p1.height < p2.height;
	}
} 

int main(void)
{
	vector<int> v1 = {1 , 10 , 34 , 23 , 123 , 0 , 56};
	sort(v1.begin() , v1.end()); //默认会从小到大排序
	sort(v1.begin() , v1.end() , greater<int>()); //greater<指定数据类型>()是系统写好的比较器默认从大到小排序 
	for(auto V : v1)
	{
		cout<<V<<endl;
	}
	
	vector<Person> v2;
	Person p1("GGBond" , 18 , 180);
	Person p2("懒洋洋" , 8 , 150);
	Person p3("熊大" , 23 , 210);
	Person p4("熊二" , 20 , 210);
	Person p5("灰太狼" , 36 , 170);
	
	v2.push_back(p1); 
	v2.push_back(p2);
	v2.push_back(p3);
	v2.push_back(p4);
	v2.push_back(p5);//将数据填充后,需要排序,按自定义顺序排序需要自定比较器 
	//按身高从小到大,如果身高一样,按照年龄降序 
	
	sort(v2.begin() , v2.end() , comperson);//自定义的比较器使用时不用写括号,直接写名字 
	
	for(auto x : v2)
	{
		cout<<x<<endl;
	} 
	
	return 0;
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值