list容器排序案例

#include<iostream>
#include<list>
#include<algorithm>//标准算法头文件
#include<string>
using namespace std;
//list容器的排序案例
//按照年龄进行升序 如果年龄相同按照身高进行降序
class person {
public:
	person(string name, int age, int hight) {
		m_name = name;
		m_age = age;
		m_hight = hight;
	}
	string m_name;
	int m_age;
	int m_hight;
};
//指定排序规则
bool compareperson(person& v1, person& v2) {
	if (v1.m_age == v2.m_age) {
		return v1.m_hight > v2.m_hight;//如果年龄一样按照身高降序排序
	}
	else
	{
		return v1.m_age < v2.m_age;//年龄不一样按照年纪升序排列
	}
}
void test() {
	list<person>l;//默认构造
	//准备数据
	person p1("a", 15, 177);
	person p2("b", 15, 178);
	person p3("c", 16, 177);
	//插入数据
	l.push_back(p1);
	l.push_back(p2);
	l.push_back(p3);
	for (list<person>::iterator it = l.begin(); it != l.end(); it++) {
		cout << "姓名" << (*it).m_name ;
		cout << "年龄" << it->m_age ;//迭代器可以当成指针来对待
		cout << "身高" << (*it).m_hight << endl;
	}
	cout << "-------------------------" << endl;
	cout << "排序后" << endl;
	l.sort(compareperson);
	for (list<person>::iterator it = l.begin(); it != l.end(); it++) {
		cout << "姓名" << (*it).m_name;
		cout << "年龄" << it->m_age;//迭代器可以当成指针来对待
		cout << "身高" << (*it).m_hight << endl;
	}
}
int main() {
	test();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值