2015-10-26 78 views
-1

我試圖根據比較函數將struct node s的一部分插入到優先級隊列中,如以下代碼片段所示。C++中Prioirty Queue操作符錯誤

struct node 
{ 
    string line; 
    int length; 
}; 

struct Pair 
{ 
    node first,second; 
}; 

struct Compare 
{ 
    bool operator()(const Pair* p1, const Pair* p2) 
    { 
     return p1->first.length > p2->first.length; 
    } 
}; 

int main() 
{ 
    ... 
    priority_queue<Pair*, vector<Pair*>, Compare> PairsQ; 
    ... 
} 

我在幾個其他類似的行中得到以下錯誤。

error: no match for ‘operator<’ (operand types are ‘const Pair’ and ‘const Pair’) { return __x < __y; }

有什麼解決辦法?即使定義了比較函數,爲什麼我會看到這個錯誤。

+1

請提供[最小的,完整的,和可覈查的示例](http://www.stackoverflow.com/help/mcve)。你發佈的錯誤提到了一個類型('ResPair'),它沒有在你的問題中列出。 – Barry

+0

另請注意,比較函數應該將值/常量引用作爲參數,而不是指針。 –

+0

@Barry,這只是對。我編輯它。還有其他功能,但它們與此錯誤無關。 – Aiyoyo

回答

1

當提供一個比較功能,像std::queue STL容器,你operator()功能應具有以下特徵:

bool operator()(const Pair& p1, const Pair& p2) 

然後(部分)你的程序想喜歡(我從Pair*改變類型Pair因爲你已經評論說,它是不是在這裏的要求):

#include <string> 
#include <queue> 

using namespace std; 

struct node { 
    string line; 
    int length; 
}; 

struct Pair { 
    node first, second; 
}; 

struct Compare { 
    bool operator()(const Pair& p1, const Pair& p2) { 
     return p1.first.length > p2.first.length; 
    } 
}; 

int main() { 
    priority_queue<Pair, vector<Pair>, Compare> PairsQ; 
}