STL 1.2 sort()

该程序定义了一个结构体`Student`,包含学号、姓名和成绩字段。通过重载`<`运算符实现自定义排序逻辑,即成绩高者优先,成绩相同时学号小的优先。利用`sort`函数和自定义比较函数`max_cmp`对学生信息进行排序。程序首先读取学生信息,然后输出排序后的结果。
摘要由CSDN通过智能技术生成

编写一个程序,基于结构体存储N个学生信息,包含学号,姓名和学科成绩,并使用模板函数sort完成对学生信息的排序:成绩高的排序靠前,若成绩相同,则学号小的排序靠前。

#include <iostream>

#include <algorithm>

#include <cstdio>

#include <cstring>

#include <string>

using namespace std;

struct Student{

    int numberID;

    char name[20];

    int score;

    Student(){}

    Student(int id_, char *name_, int score_){

        numberID = id_;

        strcpy(name, name_);

        score = score_;

    }

    void in(){

        scanf("%d %s %d", &numberID, name, &score);

    }

    void out()  {

        printf("%d %s %d\n", numberID, name, score);

    }

    bool operator < (const Student &S)const {

        if(this->score==S.score){

            return this->numberID<S.numberID;

        }

        else{

            return this->score>S.score;

 }

    }

};

bool max_cmp(Student S1, Student S2){

    if(S1.score==S2.score){

            return S1.numberID<S2.numberID;

        }

        else{

            return S1.score>S2.score;

        }

}

int main(int argc, const char * argv[]) 

{    

    int n;

    cin>>n;

   Student *S=new Student[n];

    for(int i=0;i<n;i++){

        S[i].in();

    }

    sort(S,S+n,max_cmp);

     for(int i=0;i<n;i++){

        S[i].out();

    }

    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值