Profile photo for Adam Helps

Quora, in their finite wisdom, decided that question details should cease to exist, and retroactively vandalized all their own questions to match. This answer makes little sense with the details missing, so here they are:

My code works with the < or > comparator, but will crash with <= or >=. [After] some debugging I doubt the std::sort behaves unexpectedly, so i found the strict weak ordering description in its comp. It seems that only less or greater qualifies. After some reading i still didn't get it... Can anyone explain this? Why <= or >= won't work?

Because internally, these algorithms implement "is equal to" as !(a < b) && !(b < a). If you used <= as the ordering operator, then this will return false when a == b. A broken equality check will screw up nearly any algorithm.

Similarly, they implement "is not equal to" as (a < b) || (b < a), and once again, if you provided <= as the ordering operator, then this will return false when a != b. So the equality check is broken in both directions.

The whole point of limiting the library to a less-than operator is that all of the logical operators can be implemented in terms of it:

  • <(a, b): (a < b)
  • <=(a, b): !(b < a)
  • ==(a, b): !(a < b) && !(b < a)
  • !=(a, b): (a < b) || (b < a)
  • >(a, b): (b < a)
  • >=(a, b): !(a < b)

This works as long as your provided operator meets the conditions of a strict weak ordering. The standard <= and >= operators do not.

View 2 other answers to this question
About · Careers · Privacy · Terms · Contact · Languages · Your Ad Choices · Press ·
© Quora, Inc. 2025