【问题标题】:Defining priority queue inside a class with a custom comparator function使用自定义比较器函数在类中定义优先级队列
【发布时间】:2016-09-30 17:33:54
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++ stl priority-queue


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复 :) 但是有没有办法让它不受版本限制地工作?通过将初始化转移到类构造函数来说?
    • @ant_1618,是的,你当然可以这样做。我也更新了答案以包含此变体。但是,如果您已经知道 initializationconstructor 的话,我希望您应该已经知道答案... =)
    • 我不知道 cpp 在构造函数中使用 Test() : [initialisation list] { \\ code} 隐式初始化成员变量的方式。所以,我想不出这个答案 :P 现在很清楚了 :D 谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多