Why does std :: sort () require a static comparison function?

I am solving a problem in Leetcode OJ. I wrote a solution like this:

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    bool comparefunc (const Interval& a, const Interval& b) {
        return a.start < b.start;
    }
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> result;
        if(intervals.empty()) return result;

        // sort Interval vector on increasing order of start
        sort (intervals.begin(), intervals.end(), comparefunc);

        // some other stuffs
        result.push_back(intervals[0]);
        for(int i = 1; i < intervals.size(); ++i) {
            if(intervals[i].start > result.back().end) result.push_back(intervals[i]);
            else result.back().end = max(result.back().end, intervals[i].end);
        }
        return result;
    }
};

And this gives a compilation error:

    no matching function for call to 
'sort(std::vector<Interval>::iterator, std::vector<Interval>::iterator, <unresolved overloaded function type>)'

Then I changed the signature comparefuncto static(seen in another solution), for example:

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

And it worked! My question is: why should it be static?

+4
source share
2 answers

Think about how you call compareFuncoutside the class. You will always have something like

a.compareFunc(b, c)
^             ^  ^

which is 3 parameters, not 2.

sort the code is outside your class and will have to use the syntax above.

Creating a static element allows this call:

Solution::compareFunc(a, b)

which is only 2 parameters and matches the expected predicate std::sort.

(), operator< -, , , :

struct Foo
{
    bool operator<(Foo const& other) { /* ... */ }
};

int main()
{
    Foo a, b;
    a < b; // calls a.operator<(b)
}

struct Foo
{};

bool operator<(Foo const& lhs, foo const& rhs) { /* ... */ }

int main()
{
    Foo a, b;
    a < b; // calls operator<(a, b)
}
+8

static, &Solution::comparefunc :

bool (Solution::*) (const Interval& a, const Interval& b);

static, &Solution::comparefunc:

bool (*) (const Interval& a, const Interval& b);
+2

All Articles