优先队列比较 [英] Priority Queue Comparison
问题描述
我正在尝试使用自定义比较函数在c ++中声明优先级队列...
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;
这是比较功能:
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?
谢谢
推荐答案
模板参数应为比较功能的类型.然后,该函数可以是默认构造的,也可以在 priority_queue
的构造函数中传递一个函数.所以尝试
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.
这篇关于优先队列比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!