score_sort

来源:互联网 发布:图布局算法 编辑:程序博客网 时间:2024/05/16 11:00

成绩排序:规则,有N个学生的数据,将学生数据按成绩高低排序,如果成绩相同则按姓名字符的字母序排序,如果姓名的字母序也相同则按照学生的年龄排序,并输出N个学生排序后的信息。

#include<stdio.h>#include<algorithm>#include<string.h>using namespace std;struct E{    char name[1001];    int age;    int score;}buf[100];bool cmp(E a,E b){//实现比较规则    if(a.score!=b.score)return a.score<b.score;//若分数不相同则分数低者在前    int tmp=strcmp(a.name,b.name);    if(tmp!=0)return tmp<0;//若分数相同则名字字典序小者在前    else return a.age<b.age;//若名字也相同则年龄小者在前}int main(){    int n;     printf("Please input student number:\n");    while(scanf("%d",&n)!=EOF){        printf("Please input name and age and score:\n");        for(int i=0;i<n;i++){            scanf("%s%d%d",buf[i].name,&buf[i].age,&buf[i].score);        }//输入        sort(buf,buf+n,cmp);//利用自己定义的规则对数组进行排序        printf("sort result:\n");        for(int i=0;i<n;i++){            printf("%s %d %d\n",buf[i].name,buf[i].age,buf[i].score);        }//输出排序后的结果    }    return 0;}
strcmp(字符串1,字符串2):

“=”,返回int 型 0

“>”, 返回int 型+1

“<”,返回int型 -1

方法二、重载运算符的使用

#include<stdio.h>#include<algorithm>#include<string.h>using namespace std;struct E{    char name[1001];    int age;    int score;    bool operator<(const E &b)const{        if(score !=b.score)return score<b.score;        int tmp=strcmp(name,b.name);        if(tmp!=0)return tmp<0;        else return age<b.age;    }}buf[1000];int main(){    int n;    while(scanf("%d",&n)!=EOF){        for(int i=0;i<n;i++){            scanf("%s%d%d",buf[i].name,&buf[i].age,&buf[i].score);        }        sort(buf,buf+n);        for(int i=0;i<n;i++){            printf("%s %d %d\n",buf[i].name,buf[i].age,buf[i].score);        }    }    return 0;}
在类外定义运算符重载函数,只能对类公有数据成员进行操作。实际上,运算符的重载有两种形式,定义为类的友元函数;定义为他将要操作的类的成员函数。前者称为友元运算符函数,后者为成员运算符函数。


0 0
原创粉丝点击