Using greater comparator in priority_queue storing pointers of custom class

61 views Asked by At

I have a priority_queue like this, instead of using the less comparison (the default of priority_queue). I want to use greater<>. So I tweak the code like this

priority_queue<EncodingNode*, vector<EncodingNode*>, greater<Comparator>> pq;

This is the definition of my EncodingNode

class EncodingNode
{
public:
    char c;
    int freq;
    int priority;
};

This is my Comparator class:

struct Comparator
{
    bool operator()(const EncodingNode* a, const EncodingNode* b);
};

bool Comparator::operator()(const EncodingNode* a, const EncodingNode* b)
{
    // logic for comparing two EncodingNode*
    if (a->freq > b->freq)
        return true;
    else if (a->freq == b->freq)
    {
        if (a->priority > b->priority)
            return true;
    }
    return false;
}

It keeps giving me this error: cannot convert argument 1 from 'EncodingNode *' to 'const_Ty &' Is there anyway to fix this, if I remove the greater part of the code, it runs but without using greater<>, I have to somehow negate the condition inside my comparator and gives me wrong result. Is there anyway to use greater<> in this case. Thank you very much.

1

There are 1 answers

0
Alan Birtles On BEST ANSWER

std::greater converts operator()(x, y) into x > y, as Comparator doesn't implement the > operator greater<Comparator> won't compile. You don't need std::greater in this case, you just pass the comparator directly:

priority_queue<EncodingNode*, vector<EncodingNode*>, Comparator> pq;

Note that your comparator can be simplified to:

bool Comparator::operator()(const EncodingNode* a, const EncodingNode* b)
{
    return std::tie(a->freq, a->priority) > std::tie(b->freq, b->priority);
}