Hello everyone!
While solving this problem, I defined my own comparator function for sorting a vector of coordinates (represented as struct). However I got runtime error upon using the comparator function like this —
struct Point
{
int x,y;
};
int main()
{
vector<Point> v;
sort(v.begin(),v.end(), [&](Point &p1, Point &p2){
if(p1.x!=p2.x)
return p1.x<=p2.x;
return p1.y<=p2.y;
});
}
and also like this —
struct Point
{
int x,y;
};
int main()
{
vector<Point> v;
sort(v.begin(),v.end(), [&](Point &p1, Point &p2){
if(p1.x!=p2.x)
return p1.x<p2.x;
return p1.y<=p2.y;
});
}
But I got AC when I used the comparator like this —
struct Point
{
int x,y;
};
int main()
{
vector<Point> v;
sort(v.begin(),v.end(), [&](Point &p1, Point &p2){
if(p1.x!=p2.x)
return p1.x<=p2.x;
return p1.y<p2.y;
});
}
Can anyone explain why the first 2 comparator definitions gave RE but the third one gave AC?
Submission 1 (RE) — Submission 1
Submission 2 (RE) — Submission 2
Submission 3 (AC) — Submission 3
read this blog https://codeforces.me/blog/entry/70237
When you define "=" in the comparator then sorting may go in an infinite loop.
Custom comparator should return false if elements are equal.
Check this for further explanation