nameTable; // vector...">

Why is std :: less than "<"?

C ++ primer, 5th, 14.8.2, Using a library function object with 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 implementation of std :: less:

template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
  bool
  operator()(const _Tp& __x, const _Tp& __y) const
  { return __x < __y; }
};

I found out that std :: less also uses the <operator to do the job, so why <is undefined and the library ensures that less for pointer types is defined correctly, why std: is less recommended, and why std :: is less better than < .

+4
source share
1 answer

Because <not always operator<(). Only classes have operator functions, so your suggestion will not work for built-in types.

, < - , std::less ( — , , "" std::less!) :

std:: less , < .

: std::less , , .

+7

Source: https://habr.com/ru/post/1672156/


All Articles