2016-10-01 76 views
0

我需要一個比較函數用於在我的優先級隊列中比較對象。對象需要按照對象的比例進行排序。由於某些原因,RatioCompare函數不能工作/編譯。比較某個對象的功能優先級隊列C++

編譯器提供了以下錯誤:

In member function bool RatioCompare::operator()(const Item&, const Item&) const : joulethief.cpp:58 : error: passing ‘const Item’ as ‘this’ argument of double Item::getRatio() discards qualifiers joulethief.cpp:59: error: passing ‘const Item’ as this argument of double Item::getRatio() discards qualifiers

你們可以去看看?

struct RatioCompare 
{ 
    bool operator()(const Item &i1, const Item &i2) const 
    { 
     double i1value= i1.getRatio(); 
     double i2value= i2.getRatio(); 
     return i1value < i2value; 
    } 
}; 

這裏是我已經列入計劃的兩個隊列和矢量圖書館,讓我聲明,然後進行測試,看它是否正常工作範圍內的主代碼...

priority_queue<Item, vector<Item>, RatioCompare > pq; 

for(int i=0; i<n; i++) 
{ 
    pq.push(tosteal[i]); 
} 

while(!pq.empty()) 
{ 
    Item consider= pq.top(); 
    cout<< "Name: "<< consider.getName()<< "Ratio "<< consider.getRatio()<<endl; 
    pq.pop(); 
} 

好。

+0

,你看到的是什麼錯誤? –

+0

成員函數'bool RatioCompare :: operator()(const Item&,const Item&)const': joulethief.cpp:58:error:將'const Item'作爲'this'參數傳遞給'double Item :: getRatio() '丟棄限定符 joulethief.cpp:59:錯誤:將'const Item'作爲'double'參數傳遞給'double Item :: getRatio()'丟棄限定符 –

+0

您需要將'Item :: getRatio()'標記爲'const '合格。 – ArchbishopOfBanterbury

回答

1

成員函數Item::getRatio()需要作爲const否則編譯器認爲該方法可以改變一個Item實例,從而防止從傳遞時使用它,所述Item實例作爲const_reference(如你在RatioCompareoperator()都做了標記)。

所以,只要改變Item::getRatio的定義:

class Item { 
public: 
// ... 
    double getRatio() const; // marked as const, does not alter Item instances 
}; 
+0

謝謝,明白了! –