C++ sort 排序简单用法

这篇博客介绍了如何使用C++的`sort`函数进行降序排序,并展示了如何通过重载`<`运算符对包含姓名、年龄和成绩的结构体数组进行排序。示例代码详细解释了排序规则,包括成绩、姓名字母序和年龄的比较逻辑。
摘要由CSDN通过智能技术生成

一、sort降序排列

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

bool cmp(int x, int y);

int main() {
	int n;
	int data[100];
	while (cin>>n) {
		for (int i = 0; i < n; i++)
			cin >> data[i];

		sort(data, data + n, cmp);

		for (int i = 0; i < n; i++)
			cout << data[i];
	}
	
}

bool cmp(int x, int y) {
	return x > y;       //定义排序规则
}


cmp 函数返回值 true 时表示 cmp 第一个参数将会排在第二个参数前面。

二、利用重载" < "运算符来实现结构体排序

要求是:学生数据按成绩高低排序,成绩相同按姓名字符的字母序排序,姓名字母序相同按年龄排序。

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

struct E {
	char name[101];
	int age;
	int score;

	bool operator <(const E& b)const {
		if (score != b.score) return score < b.score;
		int tmp = strcmp(name, b.name);
		if (tmp != 0) return tmp < 0;
		else return age < b.age;
	}

};

int main() {
	int n;
	E data[100];
	while (cin >> n) {
		for (int i = 0; i < n; i++)
			cin >> data[i].name >> data[i].age >> data[i].score;

		sort(data, data + n);

		for (int i = 0; i < n; i++)
			cout << data[i].name << data[i].age << data[i].score;
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值