Priority Queues in C++

C++Server Side ProgrammingProgramming

As we know that the queue data structure is First in First Out data structure. The queue has some variations also. These are the Dequeue and the Priority Queue.

Here we will see one variation of queue, that is the priority queue. In this structure, each element in the queue has its own priority. When we insert item into queue, we have to assign priority value with it. It will delete the highest priority element at first. To implement priority queue one of the easiest method is using the heap data structure.

Let us see one C++ code for priority queue STL. Here the priority is assigned based on the value. So higher value will be treated as highest priority element.


insert(key, priority):
   insert key at the end of the heap
   heapify the array based on the priority
   item := root element
   root := last element from array
   heapify the array to arrange based on priority
   return item


 Live Demo

#include <iostream>
#include <queue>
using namespace std;
void dequeElements(priority_queue <int> que) {
   priority_queue <int> q = que;
      cout << << " ";
   cout << endl;
int main() {
   priority_queue <int> que;
   cout << "Currently que is holding : ";
   cout << "Size of queue : " << que.size() << endl;
   cout << "Element at top position : " << << endl;
   cout << "Delete from queue : ";
   cout << "Delete from queue : ";


Currently que is holding : 30 20 10 5 1
Size of queue : 5
Element at top position : 30
Delete from queue : 20 10 5 1
Delete from queue : 10 5 1
Updated on 10-Aug-2020 08:56:47