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

编译运行

相关推荐
code_pgf8 小时前
C++11 / C++14 / C++17 / C++20 新特性总结
c++·c++20
颜x小12 小时前
[C#] C++与c#语法对比
开发语言·c++·c#
小poop13 小时前
轮转数组:从暴力到最优,一题掌握算法复杂度分析
数据结构·算法·leetcode
汉克老师13 小时前
GESP2026年3月认证C++八级( 第三部分编程题(2、子图最短路)精讲
c++·最短路·floyd·gesp8级
abcd_zjq14 小时前
海康线扫相机使用
c++·海康
十五年专注C++开发14 小时前
C++设计一个函数来求容器元素绝对值之和的平均值
c++·模板·accumulate
SilentSlot14 小时前
【C/C++】手写 DPDK 协议栈(十一):基于 PPS、SYN 比例和源 IP 熵的 DDoS 检测
c语言·c++·tcp/ip
wabs66615 小时前
关于图论【卡码网104.建造最大岛屿的思考】
数据结构·算法·图论
王老师青少年编程15 小时前
csp信奥赛C++高频考点专项训练:【排序算法】案例9:成绩排序
c++·排序算法·csp·高频考点·信奥赛·成绩排序
程序喵大人16 小时前
【C++进阶】STL容器与迭代器 - 05 map 和 set 为什么按键保持有序
开发语言·c++·容器·迭代器·stl