list中sort排序小例子

list不支持随机访问,因此使用成员函数进行排序
对自定义数据类型排序一定要自定义规则

#include<iostream>
#include<list>
#include<string>
using namespace std;
class Person
{
public:
	Person(string name, int age, float height)
	{
		m_name = name;
		m_age = age;
		m_height = height;
	}
public:
	string m_name;
	int m_age;
	float m_height;
};

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 Print(const list<Person>& l)
{
	for (list<Person>::const_iterator it = l.begin(); it != l.end(); ++it)
	{
		cout << "名字:" << (*it).m_name << " " << "年龄:" << (*it).m_age << " " << "身高:" << (*it).m_height << endl;
	}
}

int main()
{
	list<Person> L;
	Person p1("A", 19, 180);
	Person p2("B", 21, 170);
	Person p3("C", 20, 175);
	Person p4("D", 19, 181);
	Person p5("E", 20, 180);
	L.push_back(p1);
	L.push_back(p2);
	L.push_back(p3);
	L.push_back(p4);
	L.push_back(p5);
	Print(L);
	L.sort(comparePerson);//sort为成员函数,给定规则进行排序
    //只有拥有随机访问迭代器的容器才可以使用全局排序函数sort,list不支持随机访问
	cout << "----------------------------------------" << endl;
	Print(L);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值