Why will std::sort crash if the comparison functio

2019-01-04 13:33发布

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?

2条回答
forever°为你锁心
2楼-- · 2019-01-04 14:20

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...

查看更多
We Are One
3楼-- · 2019-01-04 14:38

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.

查看更多
登录 后发表回答