文章目录
机试之排序——成绩排序
题目描述
用一维数组存储学号和成绩,然后,按成绩排序输出。
输入描述:
输入第一行包括一个整数N(1<=N<=100),代表学生的个数。
接下来的N行每行包括两个整数p和q,分别代表每个学生的学号和成绩。
输出描述:
按照学生的成绩从小到大进行排序,并将排序后的学生信息打印出来。
如果学生的成绩相同,则按照学号的大小进行从小到大排序。
示例1
输入
复制
3
1 90
2 87
3 92
输出
复制
2 87
1 90
3 92
题目用结构体解题较快速简洁,配合sort函数以及自定义的cmp比较规则
代码
代码有多种形式
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct student{
int no;//学号
int grade;//成绩
}stu[110];
//默认比较方式还可以重载结构体数组的小于号<
/*
struct student{
int no;//学号
int grade;//成绩
bool operator< (student stu) const{
if(grade == stu.grade){
return no < stu.no;
}
else{
return grade < stu.grade;
}
}
}stu[110];
*/
//上面的结构体数组还等价于下面
/*
struct student{
int no;//学号
int grade;//成绩
};
student stu[110];
*/
bool cmp(student x,student y){
if(x.grade == y.grade){
return x.no < y.no;
}
else
return x.grade < y.grade;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>stu[i].no>>stu[i].grade;
}
sort(stu,stu+n,cmp);
for(int i=0;i<n;i++){
cout<<stu[i].no<<" "<<stu[i].grade<<endl;
}
// cout<<stu[n-1].no<<" "<<stu[n-1].grade<<endl;
return 0;
}