您的位置:首页 > 理论基础 > 计算机网络

http://www.dewen.net.cn/q/16222/C++排序中的sort函数第三个参数的疑问

2016-03-10 15:23 471 查看

C++排序中的sort函数第三个参数的疑问

唐图

3 票



37

#include<stdio.h>

#include<string.h>

#include<algorithm>

using namespace std;

const int maxsize = 1000;

struct stu{

char name[100];

int age;

int score;

};

bool cmp(stu a,stu b)

{

if(a.score < b.score)

return true;

int temp = strcmp(a.name,b.name);

if(temp < 0)

return true;

if(a.age < b.age)

return true;

return false;

}

int main()

{

int n;

struct stu s[maxsize];

while(scanf("%d",&n) != EOF)

{

for(int i = 0;i < n;++i)

{

scanf("%s",&s[i].name);

scanf("%d",&s[i].age);

scanf("%d",&s[i].score);

}

sort(s,s+n,cmp);

for(int i = 0;i < n;++i)

{

printf("%s ",s[i].name);

printf("%d ",s[i].age);

printf("%d",s[i].score);

printf("\n");

}

}

return 0;

}

在这里的cmp函数,在运行时总是弹出invalid operator < 的错误,但是如果将cmp中的return true换成return a.score < b.score之类的就对了,这是为什么了?函数sort中第三个参数需要返回的不就是bool值吗?



brayden6562
编辑于2014-03-07

评论 (3) • 举报 (0) • 分享 • 链接 • 2014-03-07 

0
我用GCC 4.8.1试没问题,'invalid operator < '这些应该是编译期的错误吧。 – mdep 2014-03-07

0
@mdep 没有,已经编译通过,是在输入数据后,运行过程中,出现了这样的错误。。。 – 唐图2014-03-07

0
不会啊,我用VC6 编译表示没问题 是不是你没有输入正确 请LZ 检查一下啦。 – 撂倒1234 2014-03-07

添加评论...

2个答案
票 数


brayden


3 票



6562

最佳答案

首先申明我是java系的, 对c嘎嘎不是很懂, 但是你的问题应该是在逻辑上的.
http://www.cplusplus.com/reference/algorithm/sort/
comp Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

comp返回true, 表示第一个参数应该放在第二个参数前面, 对吧?

那你看这个:

a

score 100

name abc

age 19

b

score 100

name bac

age 20

算算cmp(a, b),

strcmp(a.name,b.name) < 0

cmp(a, b)返回true;

再算算cmp(b, a),

strcmp(b.name,a.name) > 0

a.age < b.age

cmp(b, a) = true;

更新: 看了下资料, 这里cmp类比于 小于号, 即cmp(a, b)=true 类比于 a<b; cmp(b, a) = true 于b<a. 所以是不对的.
看到了吧, a既可以放在b的前面, 也可以放在后面, 那a=b了? 但是这里要满足strict weak ordering: https://www.sgi.com/tech/stl/StrictWeakOrdering.html Two objects x and y are equivalent if both f(x, y) and f(y, x) are false 所以不满足strict weak ordering了?

手头没有C嘎嘎环境, 请试试是否是这个问题, 多谢.

更新

改为:

bool cmp(stu a,stu b)

{

if(a.score < b.score)

return true;

else if(a.score > b.score)

return false;

int temp = strcmp(a.name,b.name);

if(temp < 0)

return true;

else if(temp > 0)

return false;

if(a.age < b.age)

return true;

return false;

}

完善
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: