自定义类型,多条件排序

3.7.8 排序案例

案例描述:

  • 将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高排序
  • 规则:按照年龄进行升序,如果年龄相同按照身高进行降序
class Student
{
public:
	Student(string name, int age,int height)
	{
		this->m_name = name;
		this->m_age = age;
		this->m_height = height;
	}
	string m_name;
	int m_age;
	int m_height;
};

//指定排序规则
bool Comp(Student &stu1, Student &stu2)
{
	if (stu1.m_age == stu2.m_age)
	{
		return stu1.m_height > stu2.m_height;
	}
	else
	{
		return stu1.m_age < stu2.m_age;
	}
}

list<Student> stu;
	Student stu1("dwas",35,175);
	Student stu2("das", 45, 180);
	Student stu3("daas", 40, 170);
	Student stu4("ddsas", 25, 190);
	Student stu5("dadss", 35, 160);
	Student stu6("dcsas", 35, 200);
	stu.push_back(stu1);
	stu.push_back(stu2);
	stu.push_back(stu3);
	stu.push_back(stu4);
	stu.push_back(stu5);
	stu.push_back(stu6);
	
	for (list<Student>::iterator it = stu.begin(); it !=stu.end(); it++)
	{
		cout << (*it).m_name << " " << (*it).m_age << " " << (*it).m_height << endl;
	}
	cout << "--------------------" << endl;
	stu.sort(Comp);
	for (list<Student>::iterator it = stu.begin(); it != stu.end(); it++)
	{
		cout << (*it).m_name << " " << (*it).m_age << " " << (*it).m_height << endl;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

colorful_stars

您是我见过全宇宙最可爱的人!

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

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

打赏作者

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

抵扣说明:

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

余额充值