C++在else/if中声明一个优先级队列

C++ declare a priority queue in an else/if?

本文关键字:一个 队列 优先级 声明 else if C++      更新时间:2023-10-16

我有两个不同的优先级队列,它们使用不同的比较器。我想要一个带有布尔值的if/else来确定哪个p.q将被设置为变量(例如,"pq");

例如,我有

priority_queue<test, vector<test>, CompareTest1> pq;

我该如何将其放在if/else中?因此,如果布尔值被标记,pq将被设置为。。。

priority_queue<test, vector<test>, CompareTest2> pq;

使用不同的比较器。谢谢

这是无法完成的,因为如果您给定不同的模板参数,则两个模板的类型不同。我的建议是传递一个比较函子,它有一个布尔值,由if语句中的内容决定。例如:

struct compare {
    bool b;   
    //set this instead of the if statement and allow the function to do something different
    operator () (const test & lhs, const test & rhs) {
    }
};

优先级队列的结构不允许您寻找什么——元素在优先级队列中根据其比较器进行排序。使用不同的比较器创建优先级队列相当于创建一个全新的优先级队列。