Priority Queue

Introduction

Priority queue is a special variant of the queue which works like a heap data structure. This is very important sometimes in some situation to use this heap. As it uses heap it can store data in increasing or decreasing order. This can pull out maximum or minimum element of a list in logN time where N is the size of the list. So You can get all the elements of the array in NlogN time.

To know about HEAP click here

Header File

To use priority queue you need to first add its header by typing the following :

 #include <queue> 

By default priority queue stores data in decreasing order which allows you to pop the maximum value of the list in each operation of logN time.

Declaration

You can declare a priority queue using following code :

priority_queue < data_type > MyPriorityQueue;

This creates a priority queue nammed MyPriorityQueue of a cerrain data type.

Operations

You can do the following operation in a priority queue :

Now lets see the implementation

Implementation of the operations

Set the Minimum Number as priority ( Minimum Number Heap )

Sometimes your priority can be to pop the smallest number first. Which means if you want to keep your data in ascending order you need to declare the priority queue using the following code :

  #include <iostream> 
  #include <queue> 
  
  using namespace std; 
  
  // Function to print minimum heap priority queue
  void print_spcl_priority_queue(priority_queue < int , vector < int > , greater < int > > temp) 
  { 
      cout << "Elements of the priority_queue are :: \n" ;
      while ( !temp.empty() ) 
      { 
          cout << temp.top() << " "; 
          temp.pop(); 
      } 
      cout << '\n'; 
  } 

  int main(){
    priority_queue < int , vector < int > , greater < int > > MySpclPQ; 
    MySpclPQ.push(12);
    MySpclPQ.push(18);
    MySpclPQ.push(8);
    // After Pushing the queue will be 8 , 12 , 18
    print_spcl_priority_queue(MySpclPQ);
    // printing the priority queue
    MySpclPQ.pop(); // popping 8
    MySpclPQ.pop(); // popping 12
    MySpclPQ.pop(); // popping 18
    // Now the queue will be empty
    return 0;
  }

OUTPUT :

  Elements of the minimum_heap_priority_queue are :: 
  8 12 18 

Here we changed the argument of the queue printing function to priority_queue < int , vector < int > , greater < int > > temp To let the function know that it is a minimum heap.

Functions :

Function Work of the function
MyPQ.empty() Returns True is MyPQ is empty otherwise returns False
MyPQ.top() Returns the most prioritized (Topmost) element of the queue
MyPQ.pop() Removes the most prioritized (Topmost) element of the queue
MyPQ.push(x) Pushes x into the heap
pq1.swap(pq2) Swaps the values from pq1 to pq2