priority_queue with custom comparator as a class method

202 views Asked by At

i have code like this

priority_queue<int, std::vector<int>, decltype(&VD::CompareByDistance)> pqDistances(&VD::CompareByDistance);

where

class VD 
{
    ...
    bool CompareByDistance(int indexLeft, int indexRight) const;
};

But i get error

error C2064: term does not evaluate to a function taking 2 arguments

How can i pass class member as a compator, the thing is that i want comparator to access its instance fields. Thanks.

1

There are 1 answers

6
Baum mit Augen On BEST ANSWER
bool CompareByDistance(int indexLeft, int indexRight);

takes three arguments: The this-pointer and the both ints.

Besides this being the wrong number of arguments for the priority_queue template parameter: What instance of VD do you expect this non-static method to be called on?

A workaround for this would be "carrying" the instance with you like this:

VD v;
auto comp = [&](int i1, int i2) {return v.CompareByDistance(i1, i2);}

This comp object would now be a valid template argument for your queue. For example:

struct A{
    bool compare (int, int) const {return true;}
};

int main()
{
    A a;
    auto comp = [&](int i, int i2) {return a.compare(i, i2);};
    std::priority_queue<int, std::vector<int>, decltype(comp)> q (comp);
}