问题
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