khemukaanmol
khemukaanmol

Reputation: 27

less<T> class and less than operator '<'

In the C++ standard library set, less<T> is default functor used for the comparison. But whenever we make some user-defined data type(say using struct) and also overloads the less than operator '<' than there is no issue faced while making a set of our customized data type.

So my question is that since the set uses less<T> as default for comparison then why there is no issue once we overload the '<' less-than operator. what is the connection between '<' and less? I can understand that there will be no issue if we define a functor for our user-defined data type but I am not able to understand that why does it work out by overloading '<' operator.

And please bear my one follow up question with this that whenever creating a set for the user-defined data type, which is considered a good practice to overload a '<' operator or to define our own functor and pass it as a template parameter. for example:

set<my_type,mycompar> myset

Upvotes: 0

Views: 555

Answers (1)

cigien
cigien

Reputation: 60227

what is the connection between '<' and less?

From the reference for std::less:

Function object for performing comparisons. Unless specialized, invokes operator< on type T.

So std::less is defined in terms of operator<. So long as you can compare objects of your type with operator<, that's what std::less will use.


whenever creating a set for the user-defined data type, which is considered a good practice to overload a '<' operator or to define our own functor and pass it as a template parameter?

This depends on the use case. If operator< makes sense for the type, then you should define it for that type.

If operator< doesn't generally make sense, but is useful for some particular algorithm where you're using the set, then pass in a comparison object for that specific purpose.

Upvotes: 3

Related Questions