为什么std::sort()需要静态Compare函数
why std::sort() requires static Compare function?
我正在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);
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- #为""定义宏;静态";针对不同的上下文
- cmake如何在fedora工作站中找到boost静态库包
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- cmake在我的项目中所需的所有静态库都不成功
- C++从另一个类访问公共静态向量的正确方法是什么
- 基于boost的程序的静态链接——zlib问题
- 在静态库中嵌入类方法
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 如何在C++中获得"静态纯虚拟"功能?
- 私有类型的静态常量成员
- 使用gcc从静态链接的文件中查找可选符号
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 如何在C++中使用非静态成员函数作为回调函数
- 将静态库链接到不带-fPIC的共享库中
- 静态结构和一个定义规则
- 为什么虚函数不能是静态的和全局的?
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 为什么std::sort()需要静态Compare函数