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

时间:2016-09-30 17:33:54

标签: c++ stl priority-queue

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

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);
                                               ^

我还尝试在测试类中声明另一个比较函数,但没有效果。为什么main函数中的优先级队列编译而类中的优先级队列没有?是否为比较器定义了一个专门的类,这里唯一的工作? 谢谢。

1 个答案:

答案 0 :(得分:3)

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;
};