Priority Queues in C++


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.

Algorithm

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

Example

 Live Demo

#include <iostream>
#include <queue>
using namespace std;
void dequeElements(priority_queue <int> que) {
   priority_queue <int> q = que;
   while(!q.empty()){
      cout << q.top() << " ";
      q.pop();
   }
   cout << endl;
}
int main() {
   priority_queue <int> que;
   que.push(10);
   que.push(20);
   que.push(30);
   que.push(5);
   que.push(1);
   cout << "Currently que is holding : ";
   dequeElements(que);
   cout << "Size of queue : " << que.size() << endl;
   cout << "Element at top position : " << que.top() << endl;
   cout << "Delete from queue : ";
   que.pop();
   dequeElements(que);
   cout << "Delete from queue : ";
   que.pop();
   dequeElements(que);
}

Output

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

405 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements