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


Priority queue is an abstract data type for storing a collection of prioritized elements that supports insertion and deletion of an element based upon their priorities, that is, the element with first priority can be removed at any time. The priority queue doesn’t stores elements in linear fashion with respect to their locations like in Stacks, Queues, List, etc. The priority queue ADT(abstract data type) stores elements based upon their priorities.

Priority Queue supports the following functions

Size() − it is used to calculate the size of the priority queue as it returns the number of elements in it.

Empty() − it return true if the Priority Queue is empty and false otherwise

Insert(element) − used to insert the new element into a Priority Queue

Min() − it return the element with the smallest associated key value and display error message if Priority Queue is empty.

removeMin()− it removes the element referenced by the min() function.

Given below is a table that shows the effect of operations on a priority queue

Start
Step 1-> Declare function to display the elements in a Priority Queue
   void display(priority_queue <int> Pq)
   declare and set priority_queue <int> que = Pq
   Loop While (!que.empty())
      call que.top()
      call que.pop()
   End
Step 2-> In main()
Create object of priority_queue <int> Pq
   Call push() to insert element in a priority queue as Pq.push(1)
   Call display(Pq)
   Call to check the size of a priority queue Pq.size()
   Call to display the top element of a priority queue Pq.top()
   Call to remove the elements of a priority queue Pq.pop()
   Call display(Pq)
Stop

Example

 Live Demo

#include <iostream>
#include <queue>
using namespace std;
void display(priority_queue <int> Pq) {
   priority_queue <int> que = Pq;
   while (!que.empty()) {
      cout << '\t' << que.top();
      que.pop();
   }
   //cout << '\n';
}
int main () {
   priority_queue <int> Pq;
   Pq.push(1);
   Pq.push(3);
   Pq.push(5);
   Pq.push(7);
   Pq.push(9);
   cout << "The priority queue is : ";
   display(Pq);
   cout << "\nPrioriy queue size using size() : " << Pq.size();
   cout << "\nFirst element of priority queue using top(): " << Pq.top();
   cout << "\nremoving element using pop() : ";
   Pq.pop();
   display(Pq);
   return 0;
}

Output

The priority queue is : 9 7 5 3 1
Prioriy queue size using size() : 5
First element of priority queue using top(): 9
removing element using pop() : 7 5 3 1

Updated on: 23-Dec-2019

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements