使用自定义比较器函数在类中定义优先级队列

Defining priority queue inside a class with a custom comparator function

本文关键字:定义 优先级 队列 自定义 比较器 函数      更新时间:2023-10-16

我正在尝试使用自定义比较器定义优先级队列,如下所示:

typedef bool (*comp)(int,int);
bool compare(int exp1,int exp2){
    return (exp1 > exp2);
}
class test{
public:
    priority_queue<int,vector<int>,comp> test_pq(compare); // Gives compilation error
};
int main ()
{
    priority_queue<int,vector<int>,comp> pq(compare); // Compiles perfectly
    return 0;
}

这是显示

的编译错误
test.cpp:18:47: error: ‘compare’ is not a type
  priority_queue<int,vector<int>,comp> test_pq(compare);
                                               ^

我还尝试在测试类中声明另一个比较函数,但没有效果。为什么优先级队列在主要功能编译而一个类内没有?为comparator定义一个专用类是这里唯一的工作吗?谢谢你。

你在test类中的代码试图声明一个签名不正确的方法test_pq

要定义成员变量,可以在初始化时使用花括号(c++ 11要求):

class test{
public:
    priority_queue<int,vector<int>,comp> test_pq{compare};
};

要在c++ 11之前实现相同的功能,您需要为test类编写自定义构造函数:

class test
{
public:
    test()
        : test_pq(compare)
    {
        // Constructor code here
    }
private:
    priority_queue<int,vector<int>,comp> test_pq;
};