排序问题

2020-06-27  本文已影响0人  CristianoC

排序问题一般用万能的sort函数就可以搞定,一般定义一下重载的比较函数就行,经常配合结构体一起使用。sort函数在algorithm头文件里面,如果里面有要求要稳定排序的话用stable_sort函数即可

#include <iostream>
#include <algorithm>
using namespace std;
struct student{
    string name;
    int grade;
    int year;
}stu[100];
bool cmp(student a,student b){
    if(a.grade != b.grade)
        return a.grade < b.grade;
    else if(a.name != b.name)
        return a.name < b.name;
    else
        return a.year < b.year;
}
int main(){
    int n;
    while (cin>>n){
        for(int i = 0;i < n;i++){
            cin>>stu[i].name>>stu[i].year>>stu[i].grade;
        }
        sort(stu,stu+n,cmp);
        for(int i = 0;i < n;i++){
            cout<<stu[i].name<<" "<<stu[i].year<<" "<<stu[i].grade<<" "<<endl;
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读