Open In App

How to Create a Stack of Priority_Queue in C++?

In C++, std::stack is a container that follows the LIFO (Last In, First Out) rule, whereas std::priority_queue is a type of queue in which the first element is either the greatest(by default) or the smallest of all elements in the queue. In this article, we will learn how to create a stack of a priority_queue in C++.

Example:

Input:
pq1 = { 1, 2, 3, 4, 5 };
pq2 =  {1, 5, 9};

Output:
pqStack = [ {1, 5, 9},
{ 1, 2, 3, 4, 5 } ]

Stack of Priority Queues in C++

To create a stack of priority_queues in C++, we have to pass the std::priority_queue type as the template argument during the declaration of the stack.

Syntax to Declare Stack of Priority_Queues in C++

stack< priority_queue<datatype>> stack_name;

Here,

C++ Program to Create Stack of Priority Queue 

The below program demonstrates how we can create a stack of priority_queue in C++ STL.

// C++ Program to illustrate how to create a stack of
// priority_queues
#include <iostream>
#include <queue>
#include <stack>
using namespace std;

int main()
{
    // Define the type of priority_queue
    typedef priority_queue<int> PriorityQueueType;

    // Initialize two priority_queues
    PriorityQueueType pq1, pq2;
    pq1.push(1);
    pq1.push(2);
    pq1.push(3);
    pq2.push(4);
    pq2.push(5);

    // Create a stack of priority_queues
    stack<PriorityQueueType> myStack;
    myStack.push(pq1);
    myStack.push(pq2);

    // Print the stack of priority_queues
    while (!myStack.empty()) {
        PriorityQueueType& topQueue = myStack.top();
        while (!topQueue.empty()) {
            cout << topQueue.top() << ", ";
            topQueue.pop();
        }
        cout << endl;
        myStack.pop();
    }

    return 0;
}

Output
5, 4, 
3, 2, 1, 

Time Complexity: O(N), here N is the number of priority_queues.
Auxiliary Space: O(N * M), where M is the size of each priority_queue.



Article Tags :