Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

c++ - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...