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;
}

编译运行

相关推荐
C雨后彩虹5 小时前
任务最优调度
java·数据结构·算法·华为·面试
微露清风8 小时前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
CSARImage8 小时前
C++读取exe程序标准输出
c++
一只小bit8 小时前
Qt 常用控件详解:按钮类 / 显示类 / 输入类属性、信号与实战示例
前端·c++·qt·gui
一条大祥脚8 小时前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法
项目題供诗9 小时前
C语言基础(一)
c++
@areok@10 小时前
C++opencv图片(mat)传入C#bitmap图片
开发语言·c++·opencv
鸽芷咕10 小时前
【2025年度总结】时光知味,三载同行:落笔皆是沉淀,前行自有光芒
linux·c++·人工智能·2025年度总结
羑悻的小杀马特10 小时前
指尖敲代码,笔尖写成长:2025年度总结与那些没说出口的碎碎念
linux·c++·博客之星·2025年度总结
linweidong10 小时前
C++thread pool(线程池)设计应关注哪些扩展性问题?
java·数据库·c++