Still unclear about the sort function, plz help me.


  • 0
    H

    When I use the following code:

    bool cmpStart(Interval &a, Interval &b){return a.start<b.start;}
    sort(intervals.begin(),intervals.end(),cmpStart);
    

    OJ shows me "invalid use of non-static member function". So, I changed the code to:

    static bool cmpStart(Interval &a, Interval &b){return a.start<b.start;}
    

    And it is accepted.
    So, why must the compare function be static?
    Thank you.


  • 3
    S

    It is because the parameter list of a non-static member function will be modified by the compiler to add the this pointer. So the comStart function you wrote is actually like this:

    bool cmpStart(Solution *this, Interval &a, Interval &b){return a.start<b.start;}

    You could have 3 solutions:

    1. Add static keyword as you did.
    2. Move this function out of the class to the global scope.
    3. You could use Lambda which I recommend.

    sort(intervals.begin(), intervals.end(), [](const Interval &it1, const Interval &it2) {return it1.start < it2.start;});


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.