Signup/Sign In

PRIORITY QUEUE Container in C++ STL

priority_queue is just like a normal queue except the element removed from the queue is always the greatest among all the elements in the queue, thus this container is usually used to replicate Max Heap in C++. Elements can be inserted at any order and it have O(log(n)) time complexity for insertion.

Following is the syntax for creating a priority queue:

priority_queue<int> pq;

Member Function of Priority Queue

Following are some of the commonly used functions of Priority Queue Container in STL:


push function

This method inserts an element in the priority_queue. The insertion of the elements have time complexity of logarithmic time.

#include <iostream>>     
#include <queue>

using namespace std;

int main ()
{
    priority_queue<int> pq1;
    
    pq1.push(30);  // inserts 30 to pq1 , now top = 30
    pq1.push(40);  // inserts 40 to pq1 , now top = 40 ( maxinmum element)
    pq1.push(90);  // inserts 90 to pq1 , now top = 90  
    pq1.push(60);	// inserts 60 to pq1 , top still is 90	
    
    return 0;
}

pop function

This method removes the topmost element from the priority_queue (greatest element) ,reducing the size of the priority queue by 1.

#include <iostream>>     
#include <queue>

using namespace std;

int main ()
{
    priority_queue<int> pq1;
    
    pq1.push(30);  // inserts 30 to pq1 , now top = 30
    pq1.push(40);  // inserts 40 to pq1 , now top = 40 ( maxinmum element)
    pq1.push(90);  // inserts 90 to pq1 , now top = 90  
    pq1.push(60);	// inserts 60 to pq1 , top still is 90	
    
    pq1.pop();  // removes 90 ( greatest element in the queue 
    
    return 0;
}

top function

This method returns the element at the top of the priority_queue which is the greatest element present in the queue.


empty and size functions

size() returns the number of element present in the priority _queue, whereas empty() returns Boolean true if the priority_queue is empty else Boolean false is returned.


swap function

This method swaps the elements of two priority_queue.