我正在解決Leetcode OJ中的一個問題。我寫了這樣一個解決方案:爲什麼std :: sort()需要靜態比較函數?
/**
* 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
?
由於非靜態成員函數具有用於'this'一個隱含的第一參數。這是他們如何訪問其他成員。 – juanchopanza 2014-09-30 22:21:23
@ juanchopanza更多解釋請!請發表回答 – 2014-09-30 22:25:14
由於與Solution的成員函數外部相同的原因,您不能在不指定「Solution」實例的情況下調用非靜態函數comparefunc。也就是說,'Solution :: comparefunc(a,b)'在語法上不是有效的。 '&Solution :: comparefunc'是一個「指向成員函數的指針」(例如,參見http://www.parashift.com/c++-faq/pointers-to-members.html)。 – rici 2014-09-30 22:32:18