c++笔记 STL list容器_排序案例

//注意:本题要求排序时,年龄相同按身高降序
//这时一个以上条件排序为高级排序
//高级排序即:在排序规则上再进行一次逻辑规则制定
#include<iostream> 
using namespace std;
#include<list>
class person {
public:
	person(string name, int age, int height) {
		m_name = name;
		m_height = height;
		m_age = age;
	}
	string m_name;
	int m_age;
	int m_height;
};
//数据类型自定义时,此步骤必需
//指定排序规则
bool compareperson(person& p1, person& p2) {
	//按照年龄 升序
	//注意: 年龄相同时,按身高进行降序
	if(p1.m_age!=p2.m_age)
	return p1.m_age < p2.m_age;
	else {
		return p1.m_height > p2.m_height;
	}

	老师的写法,相等提前return结束
	//if (p1.m_age == p2.m_age) {
	//	//年龄相同 身高降序
	//	return p1.m_height < p2.m_height;
	//}
	//return p1.m_age < p2.m_age;
}

void test01() {
	list<person>L;
	person p1("将军", 30, 189);
	person p2("统领", 27, 185);
	person p3("伍长", 34, 177);
	person p4("亲卫", 18, 179);
	person p5("校尉", 27, 182);

	L.push_back(p1);
	L.push_back(p2);
	L.push_back(p3);
	L.push_back(p4);
	L.push_back(p5);

	for (list<person>::iterator it = L.begin(); it != L.end(); it++) {
		cout << "职位: " << (*it).m_name << " 年龄: " << (*it).m_age << " 身高: " << (*it).m_height << endl;
	}
	//排序
	cout << "-----------------------------" << endl;
	cout << "排序后: " << endl;

	//排序对象为person自定义类,故排序时需要指定排序规则
	L.sort(compareperson);

	for (list<person>::iterator it = L.begin(); it != L.end(); it++) {
		cout << "职位: " << (*it).m_name << " 年龄: " << (*it).m_age << " 身高: " << (*it).m_height << endl;
	}
}
int main() {
	test01();
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值