osource's blog

By osource, history, 3 years ago, In English

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

  • Vote: I like it
  • -9
  • Vote: I do not like it

»
3 years ago, # |
Rev. 2   Vote: I like it +20 Vote: I do not like it
»
3 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

When you define "=" in the comparator then sorting may go in an infinite loop.

»
3 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it
Always remember this