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;
}
完善
相关文章推荐
- TCP/IP协议 1 ----实验楼转
- http://www.dewen.net.cn/q/15720/这样的情况一个sql语句怎么写
- 打造平安城市精品视频监控网络
- 浅谈HTTP中Get与Post的区别
- 使用802.1X+FreeRadius+LDAP实现网络准入方案
- node.js基础模块http、网页分析工具cherrio实现爬虫
- 判断安卓设备是否连接网络
- http 500错误详细代码意义
- iOS开发网络篇—数据缓存
- 关于HttpClient(调用openstack rest接口失败)
- TCP三次握手,四次挥手的状态变化
- Unity: C# TCP Client Server TcpListener NetworkStream UDP
- 【Android】【xUtils3网络下载图片的简单操作】
- Bitnami-Redmine通过https远程连接svn
- 可扩展,兼容多种网络请求框架的方案!!!
- 统计Apache的并发请求数及其TCP连接状态
- [转] 详解http和https的作用与区别
- Apache JMeter HTTPS(S) Test Script Recorder
- Linux网络编程--定时器的学习和使用
- UNP卷一学习笔记:TCP服务器常见故障