Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::sort work when the comparison function uses greater-than (>), but not greater-than-or-equal (>=)?

Tags:

c++

c++11

On WIN32, Visual Studio 2022. When I define a vector<int> containing one hundred 0s and sort it with the code below, an exception "invalid comparator" throws.

vector<int> v(100, 0);
sort(v.begin(), v.end(), [](const int& a, const int& b)
    {
        return a >= b;
    });

However, if I use return a > b, it will execute well. Why is that?

like image 953
unknown Avatar asked Oct 20 '25 17:10

unknown


1 Answers

This is just how it is required to work. You need strict weak ordering.

For the rationale, I believe that the sufficient explanation is that this enables you to determine whether those elements are equal (useful for e.g. std::sets). <= or >= can't do that.

<= or >= can also do that, but it seems like it was just decided to use < instead of any other relation. With this decision in mind, standard library facilities are implemented and they heavily rely on it.

like image 61
Fureeish Avatar answered Oct 23 '25 06:10

Fureeish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!