How to implement Priority Queue in C++

In this C++ tutorial, we are going to discuss priority queue and its implementation in C++.

What is Priority Queue ?

Priority Queue is a container in which every element has a priority and all elements are assigned in an order such that element which has the highest priority is operated first.

Declaration :-

priority_queue< data_type > priority_queue_name ;

Let’s understand priority queue by taking an example :-

Suppose, we have elements 1, 2 , 7, 4 . Now, when these elements are inserted in priority_queue.

Priority_Queue :- 7,  4, 2, 1  

priority_queue.top() :- 7

priority_queue.push(5)                         // Now, 5 will automatically adjust in priority_queue according to its priority

 

Priority_Queue :- 7,  5, 4, 2, 1

priority_queue.pop():- 7                       // element with higher order priority will pop first

 

Priority_Queue :-  5, 4, 2, 1

priority_queue.size():- 4

Priority_queue.empty():- 0

 

Some of the operation of priority_queue are :-

1.) priority_queue :: empty() :- empty() function check whether a priority_queue is empty or not. Return 1 if empty else 0.

Ex:-

  if(!priority_queue.empty())

                              {

                                       cout<<priority_queue.top()<<endl;

                                              priority_queue.pop();

                             }

2.) priority_queue :: size() :- returns the size of priority_queue or number of elements in priority_queue        container.

Ex:-

  cout<<priority_queue.size()<<endl;

3.) priority_queue :: top() :- returns the reference of top most element of queue.

Ex:-

   cout<<priority_queue.top()<<endl;

4.) priority_queue :: push() :- add an element in priority_queue.

Ex:-

priority_queue.push(1);

adds element 1 to the priority_queue.

5.) priority_queue :: pop() :- removes the first element from the priority_queue.

Ex:-

                priority_queue.pop();

C++ Code implementation of priority_queue

#include<bits/stdc++.h>
using namespace std;

    int main()
  {
      priority_queue<int>pq;
      
       pq.push(4); // inserting element 4 in priority_queue
       pq.push(7); //  inserting element 7 in priority_queue

       pq.push(2); // inserting element 2 in priority_queue
       
       cout<<"Top element of priority_queue is :- " <<pq.top()<<endl; // printing the top element of priority_queue

        cout<<"Priority_queue is:- ";

         while(!pq.empty())
       {
           cout<<pq.top()<<" ";
           
               pq.pop();
       }
  }

Also, learn:

One response to “How to implement Priority Queue in C++”

  1. Shikha Rastogi says:

    Nice and best explained.

Leave a Reply

Your email address will not be published. Required fields are marked *