Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading