7-37 模拟EXCEL排序 (25 分)
Excel可以对一组纪录按任意指定列排序。现请编写程序实现类似功能。
输入格式:
输入的第一行包含两个正整数N(≤105) 和C,其中N是纪录的条数,C是指定排序的列号。之后有 N行,每行包含一条学生纪录。每条学生纪录由学号(6位数字,保证没有重复的学号)、姓名(不超过8位且不包含空格的字符串)、成绩([0, 100]内的整数)组成,相邻属性用1个空格隔开。
输出格式:
在N行中输出按要求排序后的结果,即:当C=1时,按学号递增排序;当C=2时,按姓名的非递减字典序排序;当C=3时,按成绩的非递减排序。当若干学生具有相同姓名或者相同成绩时,则按他们的学号递增排序。
输入样例:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
输出样例:
000001 Zoe 60
000007 James 85
000010 Amy 90
用sort函数自带的结构体排序功能就行,这里方便用全局变量
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 10005;
int n, c;
struct stu
{
char num[10];
char s[10];
int score;
};
stu st[maxn];
int compare(stu a, stu b)
{
if (c == 1)
return strcmp(a.num, b.num)<0;
else if (c == 2)
{
if (strcmp(a.s, b.s))
return strcmp(a.s, b.s)<0;
else
return strcmp(a.num, b.num)<0;
}
else
{
if (a.score != b.score)
return a.score<b.score;
else
return strcmp(a.num, b.num)<0;
}
}
int main()
{
scanf_s("%d %d", &n, &c);
for (int i = 0; i < n; i++)
//scanf_s("%s %s %d", st[i].num, st[i].s, &st[i].score);
cin >> st[i].num >> st[i].s >> st[i].score;
sort(st, st + n, compare);
for (int i = 0; i<n; i++)
printf("%s %s %d\n", st[i].num, st[i].s, st[i].score);
return 0;
}