Search code examples
c++templatespriority-queue

Template function for increasing and decreasing priority queue


I wanted to write a template function for printing increasing and decreasing priority queues. Currently I have implemented it as

void print_queue1(priority_queue<int> q, string s){
    cout << "Value of prior queue " << s << " is : [";

    while(!q.empty()){
        cout << " " << q.top() << ",";
        q.pop();
    }
    cout << "]" << endl;
}


// min-heap
void print_queue2(priority_queue<int, vector<int>, greater<int>> q, string s){
    cout << "Value of prior queue " << s << " is : [";

    while(!q.empty()){
        cout << " " << q.top() << ",";
        q.pop();
    }
    cout << "]" << endl;
}

Is there some way to write a single template function that can do this?


Solution

  • You can use a variadic function template for this. Since the logic is the same regardless of the queue type, we can just accept any type of queue like

    template <typename... Params>
    void print_queue(priority_queue<Params...> q, string s){
        cout << "Value of prior queue " << s << " is : [";
    
        while(!q.empty()){
            cout << " " << q.top() << ",";
            q.pop();
        }
        cout << "]" << endl;
    }
    

    Here, Params will be deduced from the template parameters of the supplied priority_queue for you by the compiler and it will stamp out a concrete function for each different parameter set.