返回信息流突然发现`C++`的`sort`在写自定义比较函数时不能随便写返回
比如这样时
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b) {
return true; //如果这里是return a > b就正常,直接返回true就报错。
}
int main() {
vector<int> v = { 76, 43, 3, 0, 134 };
sort(v.begin(), v.end(), cmp);
for (auto i = v.begin(); i != v.end(); i++) {
cout << *i << endl;
}
return 0;
}
```
谷歌了一下,好像有这么个限制,具体也没看明白。不知道这样设计是为什么?
这是一条镜像帖。来源:北邮人论坛 / cpp / #93861同步于 2016/11/12
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
sort自定义比较函数不能随便写返回
chenxiansf
2016/11/12镜像同步20 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
cmp(1,2) 为true, cmp(2,1)也是true。你排个序试试? 根本没法排序
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.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
http://www.cplusplus.com/reference/algorithm/sort/
vs上试了一把,编译不会报错,运行时崩了。
【 在 chenxiansf 的大作中提到: 】
: [md]
: 突然发现`C++`的`sort`在写自定义比较函数时不能随便写返回
: 比如这样时
: ...................
你这么写快排的时候不是永远都是在排一个区间,另外一个区间为空。会一直死循环下去吧。
把你的代码放在vs里面跑了下。在这里报错。
```
template<class _Pr, class _Ty1, class _Ty2> inline
bool _Debug_lt_pred(_Pr _Pred,
_Ty1&& _Left, _Ty2&& _Right,
_Dbfile_t _File, _Dbline_t _Line)
{ // test if _Pred(_Left, _Right) and _Pred is strict weak ordering
if (!_Pred(_STD forward<_Ty1>(_Left), _STD forward<_Ty2>(_Right)))
return (false);
else if (_Pred(_STD forward<_Ty2>(_Right), _STD forward<_Ty1>(_Left)))//这里报错了。
_DEBUG_ERROR2("invalid operator<", _File, _Line);
return (true);
}
```
他也不会同时比较这两个吧,该比较1,2时比较1,2,该比较2,1时比较2,1。逻辑上确实没法排序,但运行起来不应该有问题啊,只能说是这么设计的了,貌似加了个断言
【 在 xiaobing307 (小兵) 的大作中提到: 】
: cmp(1,2) 为true, cmp(2,1)也是true。你排个序试试? 根本没法排序
: ...................
看来这么设计是防止无限循环?
【 在 NachtZ (那曲闲愁) 的大作中提到: 】
: 你这么写快排的时候不是永远都是在排一个区间,另外一个区间为空。会一直死循环下去吧。
: 把你的代码放在vs里面跑了下。在这里报错。
: [md]
: ...................
你可以设置a<b返回ture是没问题的
【 在 chenxiansf (影自南飞) 的大作中提到: 】
: [md]
: 突然发现`C++`的`sort`在写自定义比较函数时不能随便写返回
: 比如这样时
: ...................
通过『我邮2.0』发布
扫了一下sgi源码,并没有加断言。
用g++编译,可以跑。。。
运行结果:
134
0
3
43
76
估计是@nuanyangyang说的未定义行为,g++和vs实现不同
【 在 chenxiansf 的大作中提到: 】
: 他也不会同时比较这两个吧,该比较1,2时比较1,2,该比较2,1时比较2,1。逻辑上确实没法排序,但运行起来不应该有问题啊,只能说是这么设计的了,貌似加了个断言