优先级队列比较
Priority Queue Comparison
我正在尝试使用自定义比较函数在 c++ 中声明优先级队列......
因此,我声明队列如下:
std::priority_queue<int,std::vector<int>, compare> pq;
这是比较函数:
bool compare(int a, int b)
{
return (a<b);
}
我很确定我以前在没有类的情况下以类似的方式这样做过,但是现在,这段代码无法编译,我得到了几个这样的错误:
type/value mismatch at argument 3 in template parameter list for 'template<class _Tp, class _Sequence, class _Compare> class std::priority_queue'
有没有办法创建与此类似的比较函数,但不使用类?
谢谢
模板参数应该是比较函数的类型。然后,该函数要么是默认构造的,要么是在 priority_queue
的构造函数中传递一个函数。所以试试
std::priority_queue<int, std::vector<int>, decltype(&compare)> pq(&compare);
或者不要使用函数指针,而是使用标准库中的函子,然后可以默认构造,无需在构造函数中传递实例:
std::priority_queue<int, std::vector<int>, std::less<int> > pq;
http://ideone.com/KDOkJf
如果您的比较函数无法使用标准库函子表示(如果您在优先级队列中使用自定义类),我建议您编写自定义函子类或使用 lambda。
您可以使用
C++11 lambda 函数。您需要创建 lambda 对象,使用 decltype
将其传递给模板,并将其传递给构造函数。它看起来像这样:
auto comp = [] (int &a, int &b) -> bool { return a < b; };
std::priority_queue<int,std::vector<int>, decltype(comp) > pq (comp);
您必须
指定函数类型并在构造函数priority_queue
实例化函数。
#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);
这
对我来说非常有效。
struct compare{
bool operator() (const int& p1,const int& p2 ){
return p1<p2;
}
};
int main(){
priority_queue<int,vector<int>, compare > qu;
return 0;
}
您可以使用 typedef。这编译得很好:
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;
}
std::priority_queue<int, std::vector<int>, bool (*)compare(int, int)> pq(compare);
是另一种方式没有提及。
相关文章:
- 带自定义比较器的最小优先级队列
- 优先级队列自定义比较器
- 优先级队列功能比较
- Cython中带有自定义比较器的优先级队列
- 优先级队列比较器[C++].
- unique_ptr比较器的优先级队列
- GCC中优先级队列的奇怪shared_ptr比较器选择
- 排序函数和优先级队列 C++ 中的比较器
- 使用 lambda 比较初始化优先级队列的方法
- 优先队列的自定义比较器
- 优先队列中比较函数的工作
- 比较优先队列中的参数
- 比较优先队列的类
- 如何使用将 const int 的运算符用作 int* 优先级队列的比较器
- 优先队列中的结构比较
- C++ 具有自定义比较函数的优先级队列在 push() 上行为不正确
- 相同的比较功能为C++中的排序和优先级队列提供不同的输出
- 优先队列未正确比较C
- 谁可以解释更多关于优先级队列C++中的比较函数
- 比较队列和堆栈的内容