字符串(struct结构体)的比较

重写Compare()函数

/*
-------------------------------------------------
   Author:       wry
   date:         2022/2/25 16:47
   Description:  String_3
-------------------------------------------------
*/

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1000+10;

struct Student {
    char name[100];
    int age;
    int score;
};

Student student[MAXN];

//学生数据按成绩从低到高排序,如果成绩相同则按姓名字符的字典序由小到大排序,如果姓名的字典序也相同则按照学生的年龄从小到大排序
bool Compare(Student a,Student b) {
    if (a.score==b.score) {
        if (strcmp(a.name,b.name)==0) {    //char[]比较大小需要用strcmp,如果相等则为0
            return a.age<b.age;     //年龄从小到大
        }
        else {
            return strcmp(a.name,b.name)<0;     //姓名从小到大
        }
    }
    else {
        return a.score<b.score;     //成绩从小到大
    }
}

int main() {
    int n;
    while (scanf ("%d",&n)!=EOF) {
        for (int i=0;i<n;i++) {
            cin >> student[i].name >> student[i].age >> student[i].score;
        }
        sort(student,student+n,Compare);
        for (int i=0;i<n;i++) {
            cout << student[i].name << " " << student[i].age << " " << student[i].score << endl;
        }
    }
    return 0;
}

  

posted @ 2022-02-25 17:03  火星架构师  阅读(130)  评论(0编辑  收藏  举报