Naman
Naman

Reputation: 404

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?

Upvotes: 1

Views: 290

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63830

The template class std::priority_queue uses three template type parameters.

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

You may use those same three parameters in your function to accept any instantiation of std::priority_queue.

template<class T, class Container, class Compare>
void print_queue(priority_queue<T,Container,Compare> q, string s){
    cout << "Value of prior queue " << s << " is : [";

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

Or, you may remove/restrict any one of them to enforce a subset of priority queues..

template<class Container, class Compare>
void print_queue(priority_queue<int,Container,Compare> q, string s){
    // This function is really only designed for priority queues of int!
    cout << "Value of prior queue " << s << " is : [";

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

Upvotes: 2

NathanOliver
NathanOliver

Reputation: 180720

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.

Upvotes: 4

Related Questions