题意
输入 个学生的语、数、英三门成绩,按下列规则排序:
- 总分高的在前。
- 若总分相同,则语文成绩高的在前。
- 若语文成绩相同,则学号(即输入次序)小的在前。
思路
首先,我们可以使用 C++ 中的struct来定义结构体类型:
struct stu{
int id;//学号
int chinese;//语文成绩
int math;//数学成绩
int english;//英语成绩
int all;//总分
};其次,我们可以用 sort 来对学生成绩进行排序。
但是, sort 无法直接对结构体进行排序。
这时,我们可以在结构体中重载 运算符:
bool operator <(const stu oth)const{
if(all!=oth.all) return all>oth.all;//按总分降序排序
if(chinese!=oth.chinese) return chinese>oth.chinese;//按语文成绩降序排序
return id<oth.id;//按学号升序排序
}然后在主程序中写上: sort(stus,stus+n); 或 sort(stus.begin(),stus.end()) 即可!
AC代码
#include<bits/stdc++.h>
using namespace std;
struct stu{
int id,chi,mat,eng,all;
void input(){
cin>>chi>>mat>>eng;
all=chi+mat+eng;
}
void output(){
cout<<id<<' '<<all<<endl;
}
bool operator <(const stu oth)const{
if(all!=oth.all) return all>oth.all;
if(chi!=oth.chi) return chi>oth.chi;
return id<oth.id;
}
};
int main(){
int n;
cin>>n;
vector<stu> stus(n);
for(int i=0;i<n;i++){
stus[i].id=i+1;
stus[i].input();
}
sort(stus.begin(),stus.end());
for(int i=0;i<5;i++) stus[i].output();
return 0;
}