王道的第1061 成绩排序 题目
#include<stdio.h>
#include<algorithm>
#include<string.h>//忘?记?写′这a句?话°了?
using namespace std;
struct student //为a什?么′开a始?加ó着?typedef不?可é以?呢?
{
char name[101];//不?知a道台?这a里?为a什?么′是?101.。£。£开a始?自?己o写′的?是?100
int age;
int score;
}buf[1000];
bool cmp(student a , student b)//注痢?意癮观?察ì此?类え?题琣使?用?的?模£板? sort函ˉ数簓的?巧é妙?使?用?,?bool cmp比括?较?函ˉ数簓的?使?用?
{
if(a.score != b.score)
{
return a.score < b.score;
}
int tmp = strcmp(a.name, b.name);//!!!!!!!important
if(tmp !=0) return tmp<0; //重?点?理え?解a
else return a.age<b.age;
}
int main()
{
int n;
//int num[1000];
//用?不?着?重?复′声Θ?明÷了?
//student student[];
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, cmp);
for(int i=0; i<n; i++)
{
printf("%s %d %d\n", buf[i].name, buf[i].age, buf[i].score);
}
}
return 0;
}
也可以直接定义该结构体的 小于运算符 来说明排序规则
Bool operator < (const E &b) const {}
这样定义 < 运算符 后,调用sort函数时,可以直接sort(buf , buf+n); 不用第三个参数了。
原因是sort函数只利用< 运算符来定序,小的在前面。 所以在调用sort函数时,不必特别指明排序规则(就是说不适用第三个参数了)