The purpose of std::less
and friends is it allows you to generalize your code. Lets say we are writing a sorting function. We start with
void sort(int * begin, int * end) { /* sort here using < /* }
So now we can sort a container we can get int*
's to. Now lets make it a template so it will work with all type
template<typename Iterator>
void sort(Iterator begin, Iterator end) { /* sort here using < /* }
Now we can sort any type and we are using an "Iterator" as our way of saying we need something that points to the element. This is all well and good but this means we require any type passed to provide a operator <
for it to work. It also doesn't let use change the sort order.
Now we could use a function pointer but that won't work for built in types as there is no function you can point to. If we instead make an additional template parameter, lets call it Cmp
, then we can add another parameter to the function of type Cmp
. This will be the comparison function. We would like to provide a default value for that so using std::less
makes that very easy and gives us a good "default" behavior.
So with something like
template<typename Iterator, typename Cmp>
void sort(Iterator begin, Iterator end,
Cmp c = std::less<typename std::iterator_traits<Iterator>::value_type>)
{ /* sort here using c /* }
It allows you to sort all built in types, any type that has a operator <
, and lets you specify any other way you want to compare elements in the data to sort them.
This is why we need std::less
and friends. It lets us make the code generic and flexible without having to write a lot of boiler plate.
Using a function object also gives us some performance benefits. It is easier for the compiler to inline a call to the function call operator then it if it was using a function pointer. It also allows the comparator to have state, like a counter for the number of times it was called. For a more in-depth look at this, see C++ Functors - and their uses.
less
, but I'd bet it also has a specialization for pointers that is far more relevant to your question. Importantly: "A specialization ofstd::less
for any pointer type yields a strict total order, even if the built-inoperator<
does not." – Morel<
operator might work the same asstd::less
, but it is not required to. – Phosphorite<
on pointers doesn't necessarily implement a strict-weak ordering", or that "std::less (...) is required to"? – Laroy