0
votes

I need a compare function to use in my priority queue to compare objects. The objects need to be sorted by the ratio of the object. For some reason the RatioCompare function won't work/compile.

The compiler gives the following error:

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

Can you guys take a look?

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

Here is the code where I declare it and then test to see if it works within the 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();
}

I have the both the queue and vector library included in the program as well.

1
What error are you seeing? - Vaughn Cato
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 - Megumi Ai
You need to mark Item::getRatio() as const qualified. - sjrowlinson
Tookalook! :P ... - πάντα ῥεῖ
Would I do that by putting const after the double getRatio() in my constructor for the object? - Megumi Ai

1 Answers

1
votes

The member function Item::getRatio() needs to be marked as const otherwise the compiler thinks this method can alter an Item instance, thus preventing you from using it when you pass said Item instance as a const_reference (as you have done in operator() of RatioCompare).

So, just change the definition of Item::getRatio to:

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