Reputation: 165
I am having trouble understanding the following code. I understand the concept of a user-defined comparison is to sort an object in a certain way, but I don't understand how this code works.
struct P {
int x, y;
bool operator<(const P &p) {
if (x != p.x) return x < p.x;
else return y < p.y;
}
};
Upvotes: 0
Views: 100
Reputation: 358
The C++ compiler doesn't know what to do when you compare one instance of P with another instance so you have to define the operator in order to use it.
The boolean function for <
is to return True if the current object is smaller than the other object (p). What "smaller than" means is up for you to decide. The code that you have will return that the current object is smaller than p if it's x
value is smaller than p's x
value. If the x values are the same, then it considers if the respective y values are smaller. x > p.x
by itself is a boolean expression so the function will return if that's true of not.
Let's make a struct for an int for this to be more understandable:
struct our_int{
int x;
bool operator<(const our_int &p) {
return x < p;
}
};
Upvotes: 4