成绩排序
题目描述:
小蒜给出了班里某门课程的成绩单,请你按成绩从高到低对成绩单排序输出,如果有相同分数则名字字典序小的在前。
输入格式:
第一行为 n(0 < n < 20)n(0<n<20),表示班里的学生数目;
接下来的 n 行,每行为每个学生的名字和他的成绩, 中间用单个空格隔开。名字只包含字母且长度不超过 20 ,成绩为一个不大于 100的非负整数。
输出格式:
把成绩单按分数从高到低的顺序进行排序并输出,每行包含名字和分数两项,之间有一个空格。
题解
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
struct Stu{
char xm[100];
int cj;
}student[100];//结构体 其中定义姓名和成绩
bool compare(Stu a , Stu b){
if (a.cj != b.cj)
return a.cj > b.cj;//成绩高到低
int temp = strcmp(a.xm, b.xm);
if (temp != 0){
return temp < 0;//姓名首字母靠前
}
}
int main(){
int n;
cin>>n;
for(int i = 0; i < n ; i ++ )
cin >> student[i].xm >> student[i].cj ;//输入姓名成绩
sort(student, student+n , compare);//排序,从大到小
for(int i = 0 ; i < n ; i ++ )
cout << student[i].xm <<" "<< student[i].cj << endl ;
return 0;
}