Why C++ sort functions allow only Strict Weak Ordering?

269 Views Asked by At

Allowing only Strict Weak Ordering (or only Non-Strict Weak Ordering) lets us to order a group of elements as well as find equivalent elements among them. The second part is important in implementing sets and maps. Hence there it is ok to allow only SWO (or only NSWO). (NSWO is a total ordering unlike SWO which is a partial ordering).

But if we just want to sort a group of elements, then allowing either would still work as both answer the question 'does this order before that?'. I tried providing NSWO comparator to std::sort and it was still able to sort elements correctly.

But C++ standard require comparator to always follow SWO. Why So? Is there any caveats in letting both kind of comparators to sort function?

Examples of SWO comparator are std::less, std::greater etc. Examples of NSWO comparator are std::less_equal, std::greater_equal etc.

I was looking at the attached question. 1 This question was just talking about partial orders whereas I'm talking about total order. 2 This question asks for the cause of the crash and answers explain the cause and when it can happen. Doesn't talk about why SWO was used in first place. These justifies opening my question I think.

1

There are 1 best solutions below

0
On

In the case of Visual Studio, std::sort is a hybrid insertion sort | Hoare partition scheme quicksort. Hoare partition scheme relies on a std::less than type comparator to avoid having to check for going past the bounds of a partition (a release build won't include bounds checks, a debug build will include the checks). My guess is that a release build will fail in the simple case where there are more than 32 elements (the threshold for insertion sort) and all of the elements equal to each other.