C++ STL list自定义数据排序

C++ STL list自定义数据排序


/*说明:自定义数据类型排序,属性中有姓名、年龄、身高。
  排序规则:按照年龄进行升序排序,如果年龄相同、安装身高降序排序
*/

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

// 自定义数据类型
class PersonT 
{
public:
	PersonT(string strName, int iAge, int iHeight) 
	{
		this->m_strName = strName;
		this->m_iAge = iAge;
		this->m_iHeight = iHeight;
	}

	string m_strName; // 姓名
	int m_iAge;		  // 年龄
	int m_iHeight;    // 身高
};

// 打印列表
void PrintList(list<PersonT>& pList) 
{
	for (list<PersonT>::iterator it=pList.begin(); it!=pList.end(); it++)
	{
		PersonT pIt = *it;
		cout << "姓名:" << pIt.m_strName <<" 年龄:"<< pIt.m_iAge << " 身高:" << pIt.m_iHeight<< endl;
	}
}

// 比较函数
bool comparePerson(PersonT &p1, PersonT &p2) 
{
	if (p1.m_iAge == p2.m_iAge)
	{// 年龄相同 身高降序
		return p1.m_iHeight > p2.m_iHeight;
	} 
	
	// 年龄升序
	return p1.m_iAge < p2.m_iAge;
}

void test01()
{
	list<PersonT> personList;
	// 准备数据
	PersonT p1("刘备", 35, 175);
	PersonT p2("曹操", 45, 160);
	PersonT p3("孙权", 40, 170);
	PersonT p4("赵云", 25, 190);
	PersonT p5("张飞", 35, 170);
	PersonT p6("关羽", 35, 200);

	// 插入数据
	personList.push_back(p1);
	personList.push_back(p2);
	personList.push_back(p3);
	personList.push_back(p4);
	personList.push_back(p5);
	personList.push_back(p6);

	// 打印列表
	PrintList(personList);

	// 排序指定 比较函数
	personList.sort(comparePerson);

	cout << "------------------------" << endl;
	cout << "排序后" << endl;
	PrintList(personList);

}

int main() 
{
	test01();

	system("pause");
	return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

廷益--飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值