2014-09-30 118 views
4

我正在解決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

+4

由於非靜態成員函數具有用於'this'一個隱含的第一參數。這是他們如何訪問其他成員。 – juanchopanza 2014-09-30 22:21:23

+0

@ juanchopanza更多解釋請!請發表回答 – 2014-09-30 22:25:14

+0

由於與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

回答

8

想想你是如何在班級以外致電compareFunc的。你總是會碰到這樣的

a.compareFunc(b, c) 
^   ^^ 

這3個參數,而不是2

sort的代碼是你的類之外,將不得不使用上述語法。

使構件靜態允許此呼叫:

Solution::compareFunc(a, b) 

這是隻有2個參數和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) 
} 
2

而不static&Solution::comparefunc的類型是:

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

static&Solution::comparefunc的類型是:

bool (*) (const Interval& a, const Interval& b); 
相關問題