结构体多关键字排序,配合vector和sort

成绩排序

  • 第一关键字:成绩
  • 第二关键字:输入的前后次序
#include 
#include 
#include 
#include 

using namespace std;

struct Student
{
    string name;
    int score;
    int id;
};

bool cmp_h(Student &A, Student &B)
{
    if(A.score != B.score) 
        return A.score  > B.score;
    else 
        return A.id  < B.id;
}

bool cmp_l(Student &A, Student &B)
{
    if(A.score != B.score) 
        return A.score  < B.score;
    else 
        return A.id  < B.id;
}

int main()
{
    int n, type;
    while(cin >> n >> type)
    {
        vector stus(n);
        for(int i = 0; i < n; i ++)
        {
            cin >> stus[i].name >> stus[i].score;
            stus[i].id = i;
        }
        
        if(type == 0)
            sort(stus.begin(), stus.end(), cmp_h);
        else
            sort(stus.begin(), stus.end(), cmp_l);
        
        for(auto& stu : stus)
            cout << stu.name << " " << stu.score << endl;
    }
    
    return 0;
}
    

你可能感兴趣的:(结构体多关键字排序,配合vector和sort)