写sort的比较函数时要符合给定的要求,否则可能会出现Segmentation fault异常。
文档上对比较函数的要求:
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.
如果比较函数返回真,则表示第一个参数会排在第二个参数前面。
strict weak ordering的含义是:
For all a, comp(a, a) == false
If comp(a, b) == true then comp(b, a) == false
if comp(a, b) == true and comp(b, c) == true then comp(a, c) == true
所以,比较函数不能写成:
bool cmp(int a, int b){
return a <= b;
}
为什么呢?比较函数写成以上那样,当a和b相同时,会返回true。此时比较元素会一直遍历下去,当所有元素都是相同的情况下,就会出现访问越界,导致Segmentation fault。
解决方法:
bool cmp(int a, int b){
return a < b;
}
这样使得a和b相等的时候返回false。
参考文档:
1. C++ Sort Segmentation Fault
2. sort function C++ segmentation fault
3. Why does std::sort throw a segmentation fault on this code?
4. std::sort 排序vector 崩溃原因
5. std::sort