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

编译运行

相关推荐
以卿a12 分钟前
C++ 模板初阶
开发语言·c++
黑不溜秋的6 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
Dream it possible!8 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉8 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
柠石榴8 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
王老师青少年编程8 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
澄澈天空10 小时前
C++ MFC添加RichEditControl控件后,程序启动失败
c++·mfc
Lzc77410 小时前
C++初阶——简单实现vector
c++·简单实现vector
一个小白111 小时前
C++——list模拟实现
开发语言·c++
liuyuzhongcc11 小时前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list