当前位置: 首页 > 知识库问答 >
问题:

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

拓拔野
2023-03-14

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

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

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

共有1个答案

幸弘扬
2023-03-14

你的代码在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;
};
 类似资料:
  • priority_queue,comparator(query,d)>min_heap; main.cpp:20:7:注意:“comparator”不是文字,因为: class comparator{ main.cpp:20:7:注意:“comparator”不是聚合,没有普通的默认构造函数,也没有不是复制或移动构造函数的constexpr构造函数 Main.cpp:92:65:注意:应为类型,但

  • 我使用的是PriorityQueue和我自己的比较器,但最终结果并不总是好的。我应该按平均成绩、姓名、身份证进行排序。最后,它应该返回队列中剩余的名称。其余的名字都很好,但顺序不同。输入(名称、平均等级、识别号): 预期产出: 我的结果: 你能帮我找出问题所在吗?提前谢谢你!

  • 考虑下面的优先级类声明<代码>类优先级队列 我的想法: 我能想到的一件事是,这将强制优先级队列使用对象比较器,并且不会提供实现其自定义比较器的能力,因为类的用户可能希望基于某个不同的比较器构建队列。

  • 由于我对优先级队列的了解有限,所以我尝试实现它,但只能在asc或desc值xx中排序,这不是必需的。 我的方法是 请分享一些想法/方法。 看来很遗憾,我无法为我的情况提供所需的比较器。 不过,还是要在期待中感谢你

  • 我不理解的是返回或的含义。如果返回,则哪个元素首先被推送到队列中,如果返回则是哪个元素?

  • 这是我得到的错误: 在模板中:“std::priority_queue ,std::vector >”的初始化没有匹配的构造函数,(lambda位于