为什么std::sort()需要静态Compare函数

why std::sort() requires static Compare function?

本文关键字:静态 Compare 函数 std sort 为什么      更新时间:2023-10-16

我正在Leetcode OJ中解决一个问题。我写了一个这样的解决方案:

/**
 * 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;
    }
};

这会产生编译错误:

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

然后我用static(在其他人的解决方案中看到)更改了comparefunc签名,比如:

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

它成功了!我的问题是——为什么它需要static

想想如何在类外调用compareFunc。你总是会有类似的东西

a.compareFunc(b, c)
^             ^  ^

这是3个参数而不是2个。

sort的代码在您的类之外,必须使用上面的语法。

使成员静态允许此调用:

Solution::compareFunc(a, b)

这仅仅是2个参数并且与谓词CCD_ 6期望的匹配。

这就是为什么(例如)当您将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)
}

如果没有static&Solution::comparefunc的类型为:

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

对于static&Solution::comparefunc的类型为:

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