使用C++的sort()排序

C++库函数sort()可以提供对各种类型数据的排序,有三个参数。前两项指定排序的对象,最后一项为自定义比较规则的cmp(compare)函数。

【实例1】
有一组学生的信息。给出每个学生的学号和分数,按分数从高到低排序。分数相同的,按学号从低到高排序。

输入格式:
第一行给出学生数量n。
下面给出n行学生的学号和分数,中间以空格连接。

输出格式:
输出n行学生的学号和分数,中间以空格连接。

输入样例:

5
10002 96
10005 100
10004 97
10003 97
10001 99

输出样例:

10005 100
10001 99
10003 97
10004 97
10002 96

代码:

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

struct student
{
	char id[15];
	int score;
}stu[10];

bool cmp(student x, student y)
{
	if (x.score != y.score)
		return x.score > y.score;    //分数从大到小
	else
		return strcmp(x.id, y.id) < 0;    //学号从小到大
}

int main()
{
	int n;
	cin >> n;	//学生数量
	for (int i = 0; i < n; ++i)
	{
		cin >> stu[i].id;
		cin >> stu[i].score;
	}
	sort(stu, stu + n, cmp);
	for (int i = 0; i < n; ++i)
	{
		cout << stu[i].id << " " << stu[i].score;
		cout << endl;
	}
}

【PAT A1025】
题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805474338127872

思路:
对n个考场的排序用一个大循环控制,共做n次。
在每一次中,先读取所有考生的信息,然后对该考场的考生排序和计算排名。
n次完成后,再对所有考生做一次排序和计算排名。
最后输出所要的信息。

sort()排序的方法和上面一样。

代码:

#include <iostream>
#include <algorithm>
#include <cstring>    //for g++
using namespace std;

struct student
{
	char id[13];    //考生号
	int score;    //分数
	int location_number;    //考场号
	int local_rank;    //考场内排名
	int total_rank;    //总排名
}stu[30000];

bool cmp(student x, student y)
{
	if (x.score != y.score)
		return x.score > y.score;    //分数从大到小
	else
		return strcmp(x.id, y.id) < 0;    //考生号从小到大
}

int main()
{
	int n;
	int i, j, k;
	int num = 0;    //考生人数
	cin >> n;    //考场数量
	for (i = 1; i <= n; ++i)
	{
		cin >> k;    //考场内人数

		//读入考场内所有考生的信息
		for (j = 1; j <= k; ++j)
		{
			cin >> stu[num].id;
			cin >> stu[num].score;
			stu[num].location_number = i;
			++num;
		}

		//对考场内考生排序
		sort(stu + num - k, stu + num, cmp);

		//计算考场内的排名
		stu[num - k].local_rank = 1;
		for (j = num - k + 1; j < num; ++j)
		{
			if (stu[j].score == stu[j - 1].score)
				stu[j].local_rank = stu[j - 1].local_rank;
			else
				stu[j].local_rank = j + 1 - (num - k);
		}
	}

	//对全体考生排序
	sort(stu, stu + num, cmp);

	//计算全体考生的排名
	stu[0].total_rank = 1;
	for (j = 1; j < num; ++j)
	{
		if (stu[j].score == stu[j - 1].score)
			stu[j].total_rank = stu[j - 1].total_rank;
		else
			stu[j].total_rank = j + 1;
	}

	//输出结果
	cout << num << endl;
	for (j = 0; j < num; ++j)
	{
		cout << stu[j].id << " ";
		cout << stu[j].total_rank << " ";
		cout << stu[j].location_number << " ";
		cout << stu[j].local_rank;
		cout << endl;
	}

}
posted @ 2021-01-20 14:21  MorpheusDong  阅读(399)  评论(0编辑  收藏  举报