Priority Queue in C++ Standard Template Library (STL)

In this tutorial, we are going to learn what are Priority Queues in Standard Template Library (STL). So let’s know a little about Priority Queues.

What are Priority Queues?

They are container adapters that are meant in such a way so that the first element is always the greatest in the queue and all the elements are in non-increasing order. Hence each element of the priority queue has a fixed order or it is given a fixed priority. Let’s see a code as an example for Priority Queue.

C++ Code: Priority Queue in STL

Below is given our code for priority query in STL:

#include <iostream>
#include<queue>
using namespace std;

void showpq(priority_queue<int> gq)
{
  priority_queue<int> g = gq;
  while (!g.empty()) {
    cout << '\t' << g.top();
    g.pop();
  }
  cout << '\n';
}


int main()
{
  priority_queue<int> gquiz;
  gquiz.push(1);
  gquiz.push(7);
  gquiz.push(2);
  gquiz.push(5);
  gquiz.push(3);

  cout << "The priority queue will be : ";
  showpq(gquiz);

  return 0;
}

Output:

The priority queue will be : 7 5 3 2 1

Explanation to the code:

In order to make priority queues in C++ first we need to mention the required <queue> header file. Then we need to create a priority queue using thisĀ  void showpq(priority_queue<int> gq) function.

After that, we use while condition assuming whether queue is not empty then we need to execute the queue from the top and then till the end. Then we will call the priority queue and insert 5 integer number using pop and then the priority queue will be executed in order of higher to lower elements in the output screen.

Leave a Reply

Your email address will not be published.