2013-06-22 65 views
0

我已經看過移到該thread其中談到使用這種方法用於比較:C++ STL priority_queue與結構Clearification

struct thing 
{ 
    int a; 
    char b; 

    bool operator<(const thing &o) const 
    { 
     return a < o.a; 
    } 
}; 

priority_queue<thing> pq; 

在另一方面其它用途的方法,例如這樣的:

struct Time { 
    int h; 
    int m; 
    int s; 
}; 

class CompareTime { 
    public: 
    bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2 
    { 
     if (t1.h < t2.h) return true; 
     if (t1.h == t2.h && t1.m < t2.m) return true; 
     if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true; 
     return false; 
    } 
} 

priority_queue<Time, vector<Time>, CompareTime> pq; 

雖然我用第一種方法邏輯自己,我不會放棄理解第二種方法。主要是因爲語法。我不能確定超載運營商operator()的含義。什麼是運算符重載?

另外,從cplusplus on priority_queue,我不太瞭解以下內容,主要是第二個參數。

template < class T, class Container = vector<T>, 
     class Compare = less<typename Container::value_type> > class priority_queue; 

換句話說,我不明白第二種方法及其調用約定。

此外,有什麼區別,哪種方法是首選?

回答

1

我不能確定重載操作符operator()是什麼意思。 什麼是運算符重載?

我們在這裏是函數調用運算符(see SO question)的過載,這意味着客戶端代碼可以「享受」的CompareTime類實例的比較功能:

CompareTime ct; 
if (ct(t1, t2)) 
{ 
... 
} 

我不不太瞭解以下內容,主要是第二個參數。

cplusplus參考總結相當好,模板參數:

  • 0精氨酸 - 類型的隊列內的對象。
  • 1 ARG - 爲對隊列中的底層的容器/數據結構中,通過 默認其在std矢量
  • 2 ARG - 對優先級隊列操作依賴於一些優先 比較,即,在隊列中的項之前應該是」 '另一項(也可參見Wikipedia,所以這個arg接受比較對象(函子),它意味着重載()運算符的純類的實例,默認值是std less函子,它只是'<'語義之上的包裝器(布爾2值函數對象)

//模板結構少

template<class _Ty> 
struct less : public binary_function<_Ty, _Ty, bool> 
{ 
    // functor for operator< 
    bool operator()(const _Ty& _Left, const _Ty& _Right) const 
    {  
     // apply operator< to operands 
     return (_Left < _Right); 
    } 
};