I'm trying to declare a priority queue in c++ using a custom comparison function...
So , I declare the queue as follows:
std::priority_queue<int,std::vector<int>, compare> pq;
and here's the compare function :
bool compare(int a, int b)
{
return (a<b);
}
I'm pretty sure I did this before, without a class,in a similar way, but now, this code doesn't compile and I get several errors like this :
type/value mismatch at argument 3 in template parameter list for 'template<class _Tp, class _Sequence, class _Compare> class std::priority_queue'
Is there a way to create a compare function similar to this but without using a class?
Thanks
The template parameter should be the type of the comparison function. The function is then either default-constructed or you pass a function in the constructor of priority_queue
. So try either
std::priority_queue<int, std::vector<int>, decltype(&compare)> pq(&compare);
or don't use function pointers but instead a functor from the standard library which then can be default-constructed, eliminating the need of passing an instance in the constructor:
std::priority_queue<int, std::vector<int>, std::less<int> > pq;
If your comparison function can't be expressed using standard library functors (in case you use custom classes in the priority queue), I recommend writing a custom functor class, or use a lambda.