How do I pass a 'general' priority_queue as function argument in c++

In my main function, I have a bunch of priority_queues all of them have int in them, but some have less<int>, others have greater<int>:

//std:: removed for clarity
priority_queue<int, vector<int>, less<int>> pq1;
priority_queue<int, vector<int>, greater<int>> pq2;

I wish to make a function that accepts two priority_queue by reference and pops the first and puts into the second.

But, this gives me an error:

void f(priority_queue<int> &from, priority_queue<int> &to) {
    int x = from.top();
    from.pop();
    to.push(x);
}

When passing my priority_queues into the function, it gives me an error. (no matching function for call)

How can I fix this without making four separate functions for ‘greater’ and ‘less’ combinations?

>Solution :

Just create a function template:

template<class C1, class L1, class C2, class L2>
void f(std::priority_queue<int, C1, L1> &from, std::priority_queue<int, C2, L2> &to) {
    int x = from.top();
    from.pop();
    to.push(x);
}

Leave a Reply