pat 甲级 1028 List Sorting

结构体排序问题,解决了上次出现的不知道相等的怎么排的问题

//在构造函数里排,不在外面弄
bool my(stu a, stu b){
    if(a.score == b.score) return a.num < b.num;
    return a.score < b.score;
}

多用scanf printf
所以不能用 string 就用char存名字
比较时用strcmp函数
头文件 cstring

strcmp( a, b );

a == b 返回  0
a > b  返回 >0
a < b  返回 <0
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

struct stu{

    int num;
    char name[10];
    int score;

};

stu student[110000];

int n, c;

bool mynum(stu a, stu b){
    return a.num < b.num;
}

bool myname(stu a, stu b){
    if(strcmp(a.name,b.name)==0) return a.num < b.num;
    return strcmp(a.name,b.name) < 0;
}

bool myscore(stu a, stu b){
    if(a.score==b.score) return a.num < b.num;
    return a.score < b.score;
}

int main(){

    scanf("%d%d",&n, &c);
    int i;
    for(i=0; i<n; i++)      
    scanf("%d%s%d",&student[i].num,&student[i].name,&student[i].score);

    switch(c){

        case 1: sort(student,student+i,mynum);
                for(int j=0; j<i; j++) 
                printf("%06d %s %d\n",student[j].num,student[j].name,student[j].score);             
                break;

        case 2: sort(student,student+i,myname);
                for(int j=0; j<i; j++) 
                printf("%06d %s %d\n",student[j].num,student[j].name,student[j].score);
                break;
        case 3: sort(student,student+i,myscore);
                for(int j=0; j<i; j++) 
                printf("%06d %s %d\n",student[j].num,student[j].name,student[j].score);
                break;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/mdzz_z/article/details/81530944