C++复合数据类型进行比较排序的方法

#include<iostream>
#include <algorithm>
using namespace std;

//方法一:自定义比较子
struct E {
	char name[10];
	int age;
	int score;

};

//按照成绩排序,成绩相同按照名字排序,否则按照年龄排序
bool cmp(E a, E b) {
	if (a.score != b.score)
	{
		return a.score < b.score;
	}
	else {
		int temp = strcmp(a.name, b.name);
		if (temp != 0)
			return temp < 0;
		else
			return a.age < b.age;
	}
}

int main() {
	E student[100] ;
	sort(student, student+100, cmp);//按照定义的规则进行排序
	E2 student2[100];
	sort(student2, student2 + 100);
}


//方法二:通过重载小于等号进行比较
struct E2 {
	char name[10];
	int age;
	int score;
	bool operator< (const E2 &b)const {
		if (this->score != b.score)
			return  this->score < b.score;
		else {
			int temp = strcmp(this->name, b.name);
			if (temp != 0)
				return temp < 0;
			else
				return  this->age < b.age;
		}
	}

};

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值