What does this code do?
struct P {
int x, y;
bool operator<(const P &p) {
if (x != p.x) return x < p.x;
else return y < p.y;
}
};
What does this code do?
struct P {
int x, y;
bool operator<(const P &p) {
if (x != p.x) return x < p.x;
else return y < p.y;
}
};
It creates a structure on whose object you can use operator ‘<’.
P obj1;
P obj2;
obj1.x=1;
obj1.y=2;
obj2.x=3;
obj2.y=4;
obj1<obj2 will return True since obj1.x!=obj2.x and obj1.x < obj2.x
The bool operator<
part is probably for sorting.
You can use pair<int,int>
to accomplish this instead.
this si an operator overloading in c++
suppose you want to compare two values x1,y1 with x2,y2
and let p1 have x1,y1 and p2 have x2,y2
here by operator overloading you can directly compre p1 < p2 which is same as
if(x1!=x2)x1<x2 else y1<y2.
this can handle prettly in c++ with pair and comparators as @psaini72 said.
http://fusharblog.com/3-ways-to-define-comparison-functions-in-cpp/