56 list容器-排序案例

#include<iostream>
#include<deque>
#include<vector>
#include<stack>
#include<algorithm>
#include<Queue>
#include<ctime>
#include<list>
using namespace std;
//list容器的排序案例 对于自定义的数据类型做排序
//按照年龄进行升序,如果年龄相同按照身高进行排序

class Person
{
public:
	Person(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;
};

void printList(const list<Person>&L)
{
	for (list<Person>::const_iterator it = L.begin(); it != L.end(); it++)
	{
		cout<<"name: " << (*it).m_Name << " age: "<<(*it).m_Age<<" height: "<<(*it).m_Height;
		cout << endl;
	}
	
}

//指定排序规则
bool ComparePerson(Person& p1, Person& p2)
{
	//按照年龄升序
	if (p1.m_Age == p2.m_Age)
	{
		return p1.m_Height > p2.m_Height;
	}
	else
	{
		return p1.m_Age < p2.m_Age;
	}
	
}
void test01()//反转
{
	list<Person>L;

	Person P1("a", 18,160);
	Person P2("f", 38,169);
	Person P3("b", 38,172);
	Person P4("d", 38,158);
	Person P5("h", 88,188);
	Person P6("c", 28,135);

	L.push_back(P1);
	L.push_back(P2);
	L.push_back(P3);
	L.push_back(P4);
	L.push_back(P5);
	L.push_back(P6);
	cout << "排序之前:" << endl;
	printList(L);
	cout << "----------------------" << endl;

	cout << "排序之后: " << endl;
	L.sort(ComparePerson);
	printList(L);
}


int main()
{
	test01();
	//test02();
	system("pause");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值