比较c++中对象优先队列的函数

Compare function for an object Priority Queue C++

本文关键字:函数 优先队列 对象 c++ 比较      更新时间:2023-10-16

我需要一个比较函数在我的优先级队列中使用来比较对象。对象需要按对象的比例排序。由于某些原因,RatioCompare函数无法工作/编译。

编译器给出如下错误:

成员函数bool RatioCompare::operator()(const Item&, const Item&) const: joulethief.cpp:58: error: passing ' const Item '作为double Item::getRatio()的' this '参数丢弃了限定符joulethief.cpp:59: error: passing ' const Item '作为double Item::getRatio()this参数丢弃了限定符

你们能看一下吗?

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

下面是我声明它的代码,然后测试它是否在main中工作…

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();
}

我在程序中也包含了队列和向量库。

成员函数Item::getRatio()需要标记为const,否则编译器认为该方法可以改变Item实例,从而阻止您在将所述Item实例传递为const_reference时使用它(就像您在RatioCompareoperator()中所做的那样)。

Item::getRatio的定义改为:

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