C++学习之list容器高级排序 - 排序案例

1、案例描述:
将student自定义数据类型进行排序,student中属性有姓名、年龄、身高,体重

2、排序规则:
按照年龄进行升序,如果年龄相同按照身高进行降序,如果年龄身高都相同按照体重进行降序

3、示例代码

#include<iostream>
#include<string>
#include<list>
using namespace std;


class student//要插入容器的数据类型
{
public:
	student(string name,int age,int height,int weight)
	{
		this->m_name = name;
		this->m_age = age;
		this->m_height = height;
		this->m_weight = weight;
	}
	string m_name;
	int m_age;
	int m_height;
	int m_weight;
};


void printfList(const list<student> L)
{
	for (list<student>::const_iterator it = L.begin();it != L.end();it++)
	{
		cout << it->m_name << " " << it->m_age << " " << it->m_height <<" "<< it->m_weight << endl;
	}
	cout << endl;
}


//自定义数据类型的排序,要指定排序规则(高级排序)
bool Compare(student& s1, student& s2)
{
	if (s1.m_age == s2.m_age)//如果年龄相同,按照身高降序,否则按年龄升序
	{
		return s1.m_height > s2.m_height;//前边的数大于后边的数,降序
	}
	else
	{
		return s1.m_age < s2.m_age;//前边的数小于后边的数,升序
	}
}


bool Compare1(student& s1, student& s2)//可以增加多个排序条件,无非就是多加几个判断
{
	if ((s1.m_height == s2.m_height) && (s1.m_age == s2.m_age))//如果年龄身高都相同,按照体重进行降序
	{
		return s1.m_weight > s2.m_weight;
	}

	if (s1.m_age == s2.m_age)//如果年龄相同,按照身高降序,否则按年龄升序
	{
		return s1.m_height > s2.m_height;//前边的数大于后边的数,降序
	}
	else
	{
		return s1.m_age < s2.m_age;//前边的数小于后边的数,升序
	}
	
	
}


int main()
{
	
	list<student> L;

	student s1("张三", 20, 168, 150);
	student s2("李四", 19, 169, 120);
	student s3("王五", 21, 175, 180);
	student s4("赵六", 19, 169, 200);
	student s5("钱七", 22, 175, 130);
	student s6("王八", 22, 168, 140);
	student s7("王九", 19, 169, 140);

	L.push_back(s1);
	L.push_back(s2);
	L.push_back(s3);
	L.push_back(s4);
	L.push_back(s5);
	L.push_back(s6);
	L.push_back(s7);

	printfList(L);//排序前
	L.sort(Compare1);
	printfList(L);//排序后

	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值