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

编译运行

相关推荐
ShineWinsu几秒前
对于Linux:文件操作以及文件IO的解析
linux·c++·面试·笔试·io·shell·文件操作
十五年专注C++开发25 分钟前
Oat++: 一个轻量级、高性能、零依赖的 C++ Web 框架
开发语言·c++·web服务·oatpp
汀、人工智能1 小时前
[特殊字符] 第67课:跳跃游戏II
数据结构·算法·数据库架构·图论·bfs·跳跃游戏ii
John_ToDebug1 小时前
惰性绑定 vs 立即注入:Chromium 扩展 API 初始化策略深度对比
c++·chrome·v8
快乐的划水a1 小时前
c++计时器类
c++
山上三树2 小时前
预处理、编译、汇编、链接详解
c++
手握风云-2 小时前
优选算法的层序之径:队列专题
数据结构·算法·leetcode
比昨天多敲两行2 小时前
C++ 哈希表
数据结构·哈希算法·散列表
2301_789015622 小时前
C++:异常
开发语言·c++·异常·异常的处理方式