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

编译运行

相关推荐
LAOLONG-C1 小时前
C语言 栈 的 描述 和 详解
c语言·数据结构·算法
Ring__Rain1 小时前
visual studio 常用的快捷键(已经熟悉的就不记录了)
c++·git·visual studio
辛姜_千尘红回1 小时前
AT_abc398_e [ABC398E] Tree Game 题解
c语言·c++·笔记·算法
啊阿狸不会拉杆1 小时前
数据结构-限定性线性表 - 栈与队列
java·c语言·数据结构·c++·python·算法
ChiaWei Lee2 小时前
【C++初学】C++核心编程(一):内存管理和引用
c++
刃神太酷啦2 小时前
基础算法篇(5)(蓝桥杯常考点)—动态规划(C/C++)
数据结构·c++·算法·leetcode·蓝桥杯·动态规划·蓝桥杯c++组
kchmmd2 小时前
基于QtC++音乐播放器whisper语音转文字歌词解析
c++·qt
444A4E2 小时前
二叉搜索树完全解析:从理论到C++手把手实现
数据结构·c++
yy_xzz3 小时前
从0到1使用C++操作MSXML
xml·c++·msxml
martian6653 小时前
C++算法优化实战:破解性能瓶颈,提升程序效率
开发语言·c++·性能优化