Why will std::sort crash if the comparison function is not as operator <?

浪尽此生 提交于 2019-12-17 02:51:30

问题


The following program is compiled with VC++ 2012.

#include <algorithm>

struct A
{
    A()
        : a()
    {}

    bool operator <(const A& other) const
    {
        return a <= other.a;
    }

    int a;
};

int main()
{
    A coll[8];
    std::sort(&coll[0], &coll[8]); // Crash!!!
}

If I change return a <= other.a; to return a < other.a; then the program runs as expected with no exception.

Why?


回答1:


std::sort requires a sorter which satisfies the strict weak ordering rule, which is explained here

So, your comparer says that a < bwhen a == b which doesn't follow the strict weak ordering rule, it is possible that the algorithm will crash because it'll enter in an infinite loop.




回答2:


The answer for xorguy is pretty good.

I would just add some quote from the standard :

25.4 Sorting and related operations [alg.sorting]

For algorithms other than those described in 25.4.3 to work correctly, comp has to induce a strict weak ordering on the values.

The term strict refers to the requirement of an irreflexive relation (!comp(x, x) for all x), and the term weak to requirements that are not as strong as those for a total ordering, but stronger than those for a partial ordering.

So xorguy explains it very well : You comp function says that a < b when a == b which doesn't follow the strict weak ordering rule...



来源:https://stackoverflow.com/questions/18291620/why-will-stdsort-crash-if-the-comparison-function-is-not-as-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!