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?
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);