C++ What's the best way to implement a Priority Queue with varying priority functions?

Viewed 318

The accepted answer I've seen for swapping out a priority queue comparator is to overload the operator in a new compare class.

class Foo
{

};

class Compare
{
public:
    bool operator() (Foo, Foo)
    {
        return true;
    }
};

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
    return 0;
}

However, I want to implement several (10+) different compare functions for queue and choose one at run time when pq is created in main(). Do I have to make 10 different compare classes or is there an easier way to do this?

2 Answers

Do I have to make 10 different compare classes or is there an easier way to do this?

You don't have to. The priority_queue requires that the comparator taking a Foo and return bool - with the default one is std::less

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

In your case, you may use a lambda, or a pointer to function for that purpose. For example,

using cmp1 = bool(*)(const Foo&, const Foo&);
bool FooCmp1(const Foo& f1, const Foo& f2)
{
     // do real comparison..
     return true;
}

priority_queue<Foo, std::vector<Foo>, cmp1> pq(FooCmp1);

Use a function for comparer template argument, pass the instance of the function to the constructor of the queue, see second constructor there.

For the type, you can use C++ function object std::function<bool(const Foo& a, const Foo& b)>, or C function pointer i.e. bool(*)(const Foo& a, const Foo& b).

Related