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

让人想犯罪 __ 提交于 2019-12-13 18:06:10

问题


I have two different priority queues that use different comparators. I would like an if/else with a boolean value to determine which p.q. will be set to a variable (for example, "pq");

For example I have

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

How would I place this in an if/else so if a boolean is flagged pq will be set like...

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

using the different comparator. Thanks.


回答1:


This cannot be done because if you give a different template param the two templates are different types. My suggestion would be to pass a compare functor that has a boolean which is determined by whatever was gonna be in that if statement. For example:

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



回答2:


The structure of a priority queue doesn't allow what you're looking for -- the elements are ordered in the priority queue according to their comparator. Creating a priority queue with a different comparator is tantamount to creating a brand new priority queue.



来源:https://stackoverflow.com/questions/20061613/c-declare-a-priority-queue-in-an-else-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!