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
std::priority_queue<int, std::vector<int>, bool (*)compare(int, int)> pq(compare);
Is another way not mentioned.
You can use C++11 lambda function. You need to create lambda object, pass it to the template using decltype
and also pass it to the constructor. It looks like this:
auto comp = [] (int &a, int &b) -> bool { return a < b; };
std::priority_queue<int,std::vector<int>, decltype(comp) > pq (comp);
You can use a typedef. This compiles very well:
typedef bool (*comp)(int,int);
bool compare(int a, int b)
{
return (a<b);
}
int main()
{
std::priority_queue<int,std::vector<int>, comp> pq(compare);
return 0;
}
This worked perfectly for me.
struct compare{
bool operator() (const int& p1,const int& p2 ){
return p1<p2;
}
};
int main(){
priority_queue<int,vector<int>, compare > qu;
return 0;
}
you have to specify function type and instantiate the function in priority_queue
constructor.
#include <functional>
bool compare(int a, int b)
{
return (a<b);
}
std::priority_queue<int, std::vector<int>,
std::function<bool(int, int)>> pq(compare);
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;
http://ideone.com/KDOkJf
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.