例如有这样一个要求,对学生的成绩非递增排序,分数相同的学生根据其名字以字典序递增排序。
一般我们会这样来处理?
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct Data
{
string name;
int score;
} stu[100];
bool cmp1(Data a,Data b)
{
if(a.score!=b.score)
return a.score>b.score;
else
return a.name<b.name;
}
...
sort(stu,stu+N,cmp1);
...
但是,string类型只能用cin,cout来输入输出,而当输入字符串数量较多时,cin,cout的使用可能会导致超时,需要使用scanf和printf进行输入输出,对应的只能使用char类型数组来存储字符串。
那么,我们的cmp()函数中就不能再使用return a. name < b. name,应变成如下形式:
#include<cstdio>
#include<cstring> //提供strcmp()函数
#include<algorithm>
using namespace std;
struct Data
{
char name[20];
int score;
} stu[100];
bool cmp2(Data a,Data b)
{
if(a.score!=b.score)
return a.score>b.score;
else
return strcmp(a.name,b.name)<0;
}
...
sort(stu,stu+N,cmp2);
...
PS.
strcmp()函数
声明
int strcmp(const char *str1, const char *str2)
参数
- str1 – 要进行比较的第一个字符串。
- str2 – 要进行比较的第二个字符串。
返回值
该函数返回值如下:
- 如果返回值 < 0,则表示 str1 小于 str2。
- 如果返回值 > 0,则表示 str2 小于 str1。
- 如果返回值 = 0,则表示 str1 等于 str2。