Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 538
xmllmx Avatar asked Aug 17 '13 17:08

xmllmx


People also ask

Why does the std::sort receive a function?

std::sort() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and (by default) sorts the iterable in ascending order. The function can also​ be used for custom sorting by passing in a comparator function that returns a boolean.

How does std::sort work?

The std::sort is a sorting function that uses the Introsort algorithm and have the complexity of O(N log(N)) where N= std::distance(first, last) since C++11 and the order of equal elements is not guaranteed to be preserved[3]. The gcc-libstdc++ also uses Introsort algorithm.

Is std::sort fast?

In general, std::sort is indeed faster than qsort because of a couple of these things: qsort operates on void* , which first requires a dereference, and second requires the size of the data type to perform the swaps.


1 Answers

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.

like image 197
xorguy Avatar answered Sep 18 '22 19:09

xorguy