2016-10-01 78 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

谢谢,明白了! –