Reputation: 73
I'm new to Userdefined Comparison Operator. I was reading a book where the following example is mentioned :
struct P {
int x, y;
bool operator<(const P &p) {
if (x != p.x)
return x < p.x;
else
return y < p.y; }
};
I want to understand bool operator<(const P &p)
.
Particularly i understand that bool
is the return type of the operator i.e. return value is either true
or false
.
But I am confused , what is the significance of < in operator<
and how does this operator is actually working? What values are being compared?
Upvotes: 0
Views: 431
Reputation: 506
P a, b;
bool ret = a < b;
It actually is:
P a, b;
bool ret = a.operator<(b); // And < in operator<: x.operator<(p.x)
Did this help you to a better understanding?
Upvotes: 1
Reputation: 365
So you have a struct with two integers. X and Y. What the code above is saying is if X in the struct you're in (also known as "this") is not equal to the x in the struct passed in (p) then do a regular less than comparison between x and p's x. If they are equal, then compare the y of this to p's y.
The significance of "<" in "operator<" is to let the compiler know you're overloading the "<" operator allowing you to use it to compare to structs of type P. If you don't overload the < operator for a custom type you cannot use it to compare two of those objects.
Upvotes: 0