I'll point out that this is consistent with other parts of std, such as sort and map, which all order things based on a functor which satisfies Compare. The same question can be extended to all these things.
What is the reason?
The original author, and the standards committee, thought that it was a more natural way of expressing ordering.
There are some problems with using three way compare via int.
int has more than three values. You therefore have to do further arithmetic on the return value.
- It's easier to fall into undefined behaviour
struct three_way_compare
{
int operator()(int lhs, int rhs) { return lhs - rhs; }
// Undefined behaviour when rhs is a large positive value and lhs is a large negative value
}
You can synthesize three way comparison by calling your functor twice. The reference defines the requirements using
equiv(a, b), an expression equivalent to !comp(a, b) && !comp(b, a)
Note that for C++20, three way comparison is being added to the language with operator <=>. I'm not sure if existing algorithms are being changed to utilise it, when available.