题目要求
小蒜所在的学校一开学就进行了一次摸底考试。摸底考试考了语文、数学、英语、科学共四门课程。
小蒜的老师汇总成绩后列出了成绩单,其中包括每个同学的姓名和四科的成绩。现在老师希望表扬一下每门课程考试得分前四名和总分前四名的同学,同分数的情况下,名字字典序更小的先表扬。
请你帮助老师写一个程序,快速完成这件事情吧。
算法分析
这道题目考察了sort排序cmp函数的编写,主要的坑在名字字典排序那里,这个我们可以使用头文件为cstring的strcmp函数,这里第一个小于第二个值返回-1,等于的话返回0,大于的话返回1,我们按照从小到大的顺序排列的话就是比较这两个要返回-1的值
if(x.grade1==y.grade1) return strcmp(x.name,y.name)<0;
代码解析
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
struct student{
char name[105];
int grade1;
int grade2;
int grade3;
int grade4;
};
bool cmp1(student x,student y){
if(x.grade1==y.grade1) return strcmp(x.name,y.name)<0;
return x.grade1>y.grade1;
}