优先级队列比较

Priority Queue Comparison

本文关键字:比较 队列 优先级      更新时间:2023-10-16

我正在尝试使用自定义比较函数在 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);

是另一种方式没有提及。