1. 从代码角度来看
当元素数量大于 _S_threshold(在STL中,默认值为16)时,std::sort() 将使用 快速排序(quicksort)。
以下代码是快速排序中的 __unguarded_partition 函数。
template<typename _RandomAccessIterator, typename _Tp, typename _Compare>
_RandomAccessIterator
__unguarded_partition(_RandomAccessIterator __first,
_RandomAccessIterator __last,
const _Tp& __pivot, _Compare __comp)
{
while (true)
{
while (__comp(*__first, __pivot))
++__first;
--__last;
while (__comp(__pivot, *__last))
--__last;
if (!(__first < __last))
return __first;
std::iter_swap(__first, __last);
++__first;
}
}
如果 arg1 == arg2,比较函数返回 true,则 __first 迭代器将继续向右移动,程序将越界并导致核心转储。
while (__comp(*__first, __pivot))
++__first;
因此,如果arg1 == arg2,比较函数必须返回false。
2. 从算法逻辑的角度来看
如果比较函数使用operator<=,那么对于相等的值,它将返回true。
如果测试10B是否等同于10A,则自然使用比较函数。
在这个例子中,这是operator<=。
它检查这个表达式是否为真:
!(10A<= 10B)&&!(10B<= 10A) //test 10Aand 10B for equivalence
十进制数字10A和10B都是10,因此很明显10A <= 10B成立。同样明显的是,10B <= 10A也成立。因此上述表达式可以简化为
!(true)&&!(true)
并且这简化为
false && false
这种说法是错误的。也就是说,测试得出10A和10B不相等,因此不同。
此外,任何比较函数返回相等值为true的情况都会做同样的事情。 根据定义,相等的值并不等价!
这不很酷吗?
您还可以参考<< Effective STL>>,条款21:始终使比较函数对于相等的值返回false。