Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

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:

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 use operator < to do the work, so why < is undefined and library guarantees that less on pointer types is well defined, why is std:less recommended, and why is std::less better than <.

like image 337
cong Avatar asked Mar 13 '17 11:03

cong


People also ask

Why use std:: less?

The std::less is a is a member of the functional class (<functional. h>) used for performing comparisons. It is defined as a function object class for less than inequality comparison which returns a boolean value depending upon the condition. This can be used to change the functionality of the given function.

What is std :: Any used for?

std::any Class in C++ any is one of the newest features of C++17 that provides a type-safe container to store single value of any type. In layman's terms, it is a container which allows one to store any value in it without worrying about the type safety.


1 Answers

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.

like image 84
Lightness Races in Orbit Avatar answered Oct 16 '22 01:10

Lightness Races in Orbit