机试之排序——成绩排序

机试之排序——成绩排序

https://www.nowcoder.com/practice/3f27a0a5a59643a8abf0140b9a8cf1f7?tpId=40&tqId=21340&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

题目描述


用一维数组存储学号和成绩,然后,按成绩排序输出。
输入描述:
输入第一行包括一个整数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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李霁明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值