list容器排序实例

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

class person
{
public:
	person(string name,int age, int height)
	{
		this->myname = name;
		this->myage = age;
		this->myheight = height;
	}
	string myname;
	int myage;
	int myheight;
 } ; 
 
void printperson(list<person> &L)
{
	for(list<person>::iterator it=L.begin();it!=L.end();it++)
	{
		cout<<"姓名:"<<(*it).myname<<"  年龄: "<<(*it).myage<<"  身高: "<<(*it).myheight<<endl;
	}
}


bool compareperson(person &p1,person &p2)
{
	//按年龄升序,年龄相同则按照身高降序
	if(p1.myage == p2.myage) 
	{
		return p1.myheight>p2.myheight;
	}
	else
	{
		return p1.myage<p2.myage;
	}
	
}
void test1()
{
	list<person> L;
	
	person p1("刘备",35,175);
	person p2("曹操",45,180);
	person p3("孙权",40,170);
	person p4("赵云",25,195);
	person p5("张飞",35,160);
	person p6("关羽",35,200);
	
	L.push_back(p1);
	L.push_back(p2);
	L.push_back(p3);
	L.push_back(p4);
	L.push_back(p5);
	L.push_back(p6);
	printperson(L); 

/*
姓名:刘备  年龄: 35  身高: 175
姓名:曹操  年龄: 45  身高: 180
姓名:孙权  年龄: 40  身高: 170
姓名:赵云  年龄: 25  身高: 195
姓名:张飞  年龄: 35  身高: 160
姓名:关羽  年龄: 35  身高: 200
*/
	
	//排序
	cout<<"排序后:"<<endl; 
	L.sort(compareperson);
	printperson(L); 
/*
姓名:赵云  年龄: 25  身高: 195
姓名:关羽  年龄: 35  身高: 200
姓名:刘备  年龄: 35  身高: 175
姓名:张飞  年龄: 35  身高: 160
姓名:孙权  年龄: 40  身高: 170
姓名:曹操  年龄: 45  身高: 180
*/
}

int main()
{
	test1();
	return 0;
 } 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值