Priority Queue Comparison

大城市里の小女人 提交于 2019-12-31 19:19:08

问题


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


回答1:


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.




回答2:


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



回答3:


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



回答4:


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



回答5:


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

Is another way not mentioned.




回答6:


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


来源:https://stackoverflow.com/questions/20826078/priority-queue-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!