list容器排序案例

案例描述:将Perspn自定义数据类型进行排序,Person中属性有姓名、年龄、身高

排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序

代码示例

cpp 复制代码
#include <iostream>
#include <string.h>
#include <iterator>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <bitset>
#include <ctime>
#include <stack>
#include <queue>
#include <list>
using namespace std;

class  person 
{
public:
	person(string name, int age, int height)
	{
		this->name = name;
		this->age = age;
		this->height = height;
	}
	int age;
	string name;
	int height;
};


bool  comparePerson(person &p1,person &p2)
{
	//按照年龄进行升序
	if (p1.age == p2.age)
	{
		//如果年龄相同按照身高进行降序
		return p1.height > p2.height;
	}
	else
	{
		return p1.age < p2.age;
	}
}

void print(list<person>& p)
{
	for (list<person>::iterator it = p.begin(); it != p.end(); it++)
	{
		cout << "姓名: " << it->name << " 年龄: " << it->age << " 身高: " << it->height << endl;
	}
}
int main()
{
	person p1("赵信", 85, 166);
	person p2("盖伦", 67, 157);
	person p3("天海", 67, 186);
	person p4("斯沃特", 26, 130);
	person p5("安其拉", 18, 210);
	person p6("猴子", 2, 60);
	
	list<person> Plist = {p1,p2,p3,p4,p5,p6};
	
	cout<< "排序前: "<< endl;
	print(Plist);
	Plist.sort(comparePerson);
	cout<< "-------------------"<< endl;
	cout<< "排序后: "<< endl;
	print(Plist);

	return 0;
}

编译运行

相关推荐
数据爬坡ing32 分钟前
从挑西瓜到树回归:用生活智慧理解机器学习算法
数据结构·深度学习·算法·决策树·机器学习
骄傲的心别枯萎1 小时前
RV1126 NO.16:通过多线程同时获取H264和H265码流
linux·c++·音视频·rv1126
落羽的落羽1 小时前
【C++】特别的程序错误处理方式——异常机制
开发语言·c++
空山新雨(大队长)1 小时前
C 语言第一课:hello word c
c++·c·exe
春蕾夏荷_7282977251 小时前
c++ 第三方库与个人封装库
c++·三方库
牵牛老人2 小时前
Qt C++ 复杂界面处理:巧用覆盖层突破复杂界面处理难题之一
数据库·c++·qt
胡耀超2 小时前
3.Python高级数据结构与文本处理
服务器·数据结构·人工智能·windows·python·大模型
云:鸢2 小时前
C语言链表设计及应用
c语言·开发语言·数据结构·链表
离越词3 小时前
C++day8作业
开发语言·c++·windows
MMjeaty3 小时前
deque容器
c++