Search code examples
c++stdcomparison-operatorsunspecified-behavior

Why is std::less better than "<" for pointers?


C++ primer, 5th, 14.8.2, Using a Library Function Object with the Algorithms:

vector<string *> nameTable;  // vector of pointers
// error: the pointers in nameTable are unrelated, so < is undefined
sort(nameTable.begin(), nameTable.end(),
     [](string *a, string *b) { return a < b; });
// ok: library guarantees that less on pointer types is well defined
sort(nameTable.begin(), nameTable.end(), less<string*>());

Then I checked the std::less implementation in libc++ (code block modified for readability):

template <class _Tp>
struct less {
    constexpr bool operator()(const _Tp& __x, const _Tp& __y) const
        {return __x < __y;}
};

I have found out that std::less also uses < to do the work, so why is < undefined for pointers and std::less isn't? Why would I use std::less?


Solution

  • Because < isn't always operator<(). Only classes have operator functions, so your suggestion would not work for the built-in types.

    Furthermore, < on pointers doesn't necessarily implement a strict-weak ordering, whereas std::less (via specialisation — what you posted isn't "all" of std::less!) is required to:

    A specialization of std::less for any pointer type yields a strict total order, even if the built-in operator< does not.

    In short: std::less works for anything that supports a less-than comparison.