user2455103
user2455103

Reputation: 515

Priority Queue Comparison

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

Upvotes: 22

Views: 46359

Answers (6)

tushar pahuja
tushar pahuja

Reputation: 77

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;
}

Upvotes: 5

brack
brack

Reputation: 79

std::priority_queue<int, std::vector<int>, bool (*)compare(int, int)> pq(compare);

Is another way not mentioned.

Upvotes: 2

leemes
leemes

Reputation: 45675

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.

Upvotes: 16

Emil Condrea
Emil Condrea

Reputation: 9973

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;
}

Upvotes: 2

Jaa-c
Jaa-c

Reputation: 5137

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

Upvotes: 11

4pie0
4pie0

Reputation: 29724

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

Upvotes: 7

Related Questions