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

编译运行

相关推荐
martian6659 分钟前
深入解析C++驱动开发实战:优化高效稳定的驱动应用
开发语言·c++·驱动开发
FMRbpm34 分钟前
用队列实现栈
数据结构·c++·新手入门
fei_sun40 分钟前
【数据结构】2021年真题
数据结构
立志成为大牛的小牛1 小时前
数据结构——五十九、冒泡排序(王道408)
数据结构·学习·程序人生·考研·算法
wangjialelele1 小时前
git工作原理、个人使用到多人协作开发与git FLOW模型
c语言·c++·git·团队开发·个人开发
papership1 小时前
【入门级-数据结构-3、特殊树:完全二叉树的定义与基本性质】
数据结构·算法
iCxhust1 小时前
__acrtused 是什么
c语言·c++·单片机·嵌入式硬件·微机原理
立志成为大牛的小牛1 小时前
数据结构——六十、快速排序(王道408)
数据结构·程序人生·考研·算法·排序算法
程序员zgh2 小时前
CMake 项目构建工具介绍
c语言·开发语言·c++·编辑器
量子炒饭大师2 小时前
一天一个计算机知识——【编程百度】向上取整
c语言·数据结构·c++·git·github