The Wayback Machine - https://web.archive.org/web/20240908181813/https://www.geeksforgeeks.org/priority-queue-in-cpp-stl/
Open In App

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

Last Updated : 09 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}).

In C++ STL, the top element is always the greatest by default. We can also change it to the smallest element at the top. Priority queues are built on the top of the max heap and use an array or vector as an internal structure. In simple terms, STL Priority Queue is the implementation of Heap Data Structure.

Syntax:

std::priority_queue<int> pq;

Example:

C++




// C++ program to demonstrate the use of priority_queue
#include <iostream>
#include <queue>
using namespace std;
 
// driver code
int main()
{
    int arr[6] = { 10, 2, 4, 8, 6, 9 };
 
    // defining priority queue
    priority_queue<int> pq;
 
    // printing array
    cout << "Array: ";
    for (auto i : arr) {
        cout << i << ' ';
    }
    cout << endl;
    // pushing array sequentially one by one
    for (int i = 0; i < 6; i++) {
        pq.push(arr[i]);
    }
 
    // printing priority queue
    cout << "Priority Queue: ";
    while (!pq.empty()) {
        cout << pq.top() << ' ';
        pq.pop();
    }
 
    return 0;
}


Output

Array: 10 2 4 8 6 9 
Priority Queue: 10 9 8 6 4 2 
max heap priority queue

Max Heap Priority Queue (default scheme)

How to create a min heap for the priority queue?

As we saw earlier, a priority queue is implemented as max heap by default in C++ but, it also provides us an option to change it to min heap by passing another parameter while creating a priority queue.

Syntax:

priority_queue <int, vector<int>, greater<int>> gq;

where,

  • ‘int’ is the type of elements you want to store in the priority queue. In this case, it’s an integer. You can replace int with any other data type you need.
  • ‘vector<int>’ is the type of internal container used to store these elements. std::priority_queue is not a container in itself but a container adopter. It wraps other containers. In this example, we’re using a vector, but you could choose a different container that supports front(), push_back(), and pop_back() methods. 
  • ‘greater<int>‘ is a custom comparison function. This determines how the elements are ordered within the priority queue. In this specific example, greater<int> sets up a min-heap. It means that the smallest element will be at the top of the queue.

In the case of max heap, we didn’t have to specify them as the default values for these are already suitable for max heap.

Example:

C++




// C++ program to demonstrate
// min heap for priority queue
#include <iostream>
#include <queue>
using namespace std;
 
void showpq(
    priority_queue<int, vector<int>, greater<int> > g)
{
    while (!g.empty()) {
        cout << ' ' << g.top();
        g.pop();
    }
    cout << '\n';
}
 
void showArray(int* arr, int n)
{
    for (int i = 0; i < n; i++) {
        cout << arr[i] << ' ';
    }
    cout << endl;
}
 
// Driver Code
int main()
{
    int arr[6] = { 10, 2, 4, 8, 6, 9 };
    priority_queue<int, vector<int>, greater<int> > gquiz(
        arr, arr + 6);
 
    cout << "Array: ";
      showArray(arr, 6);
 
    cout << "Priority Queue : ";
    showpq(gquiz);
 
    return 0;
}


Output

Array: 10 2 4 8 6 9 
Priority Queue :  2 4 6 8 9 10
min heap priority queue

Min Heap Priority Queue

Note: The above syntax may be difficult to remember, so in case of numeric values, we can multiply the values with -1 and use max heap to get the effect of min heap. Not only that we can use custom sorting method by replacing greater with custom comparator function.

Methods of Priority Queue

The following list of all the methods of std::priority_queue class:

Method

Definition

priority_queue::empty() Returns whether the queue is empty.
priority_queue::size()  Returns the size of the queue.
priority_queue::top() Returns a reference to the topmost element of the queue.
priority_queue::push()  Adds the element ‘g’ at the end of the queue.
priority_queue::pop() Deletes the first element of the queue.
priority_queue::swap() Used to swap the contents of two queues provided the queues must be of the same type, although sizes may differ.
priority_queue::emplace() Used to insert a new element into the priority queue container.
priority_queue value_type  Represents the type of object stored as an element in a priority_queue. It acts as a synonym for the template parameter.

Operations on Priority Queue in C++

1. Inserting and Removing Elements of a Priority Queue

The push() method is used to insert an element into the priority queue. To remove an element from the priority queue the pop() method is used because this removes the element with the highest priority.

Below is the C++ program for various functions in the priority queue:

C++




// C++ Program to demonstrate various
//  method/function in Priority Queue
#include <iostream>
#include <queue>
using namespace std;
 
// Implementation of priority queue
void showpq(priority_queue<int> gq)
{
    priority_queue<int> g = gq;
    while (!g.empty()) {
        cout << ' ' << g.top();
        g.pop();
    }
    cout << '\n';
}
 
// Driver Code
int main()
{
    priority_queue<int> gquiz;
    // used in inserting the element
    gquiz.push(10);
    gquiz.push(30);
    gquiz.push(20);
    gquiz.push(5);
    gquiz.push(1);
 
    cout << "The priority queue gquiz is : ";
     
    // used for highlighting the element
    showpq(gquiz);
 
    // used for identifying the size
    // of the priority queue
    cout << "\ngquiz.size() : " <<
             gquiz.size();
    // used for telling the top element
    // in priority queue
    cout << "\ngquiz.top() : " <<
             gquiz.top();
 
    // used for popping the element
    // from a priority queue
    cout << "\ngquiz.pop() : ";
    gquiz.pop();
    showpq(gquiz);
 
    return 0;
}


Output

The priority queue gquiz is :  30 20 10 5 1

gquiz.size() : 5
gquiz.top() : 30
gquiz.pop() :  20 10 5 1

Refer end for complexity analysis.

Note: Above shown is one of the methods of priority queue initialization. To know more about efficient initialization of priority queue, click here.

2. To Access the Top Element of the Priority Queue 

The top element of the Priority Queue could be accessed using the top() method.

C++




// C++ program to access the top
// element of priority queue
#include <iostream>
#include <queue>
using namespace std;
 
// Driver code
int main()
{
  // create a priority queue of int
  priority_queue<int> numbers;
 
  // add items to priority_queue
  numbers.push(1);
  numbers.push(20);
  numbers.push(7);
 
  // get the element at the top
  cout << "Top element: " <<
           numbers.top();
  return 0;
}


Output

Top element: 20

Refer end for complexity analysis.

Note: We can only access the top element in the priority queue.

3. To Check whether the Priority Queue is Empty or Not:

We use the empty() method to check if the priority_queue is empty. This method returns:

  • True – It is returned when the priority queue is empty and is represented by 1 
  • False – It is produced when the priority queue is not empty or False and is characterized by 0

Example:

C++




// C++ program to demonstrate
// Implementation of empty() function
#include <iostream>
#include <queue>
using namespace std;
 
// Driver code
int main()
{
  priority_queue<int> pqueueGFG;
  pqueueGFG.push(1);
     
  // Priority Queue becomes 1
  // check if it is empty or not
  if (pqueueGFG.empty())
  {
    cout << "Empty or true";
  }
  else
  {
    cout << "Contains element or False";
  }
  return 0;
}


Output

Contains element or False

Refer end for complexity analysis.

4. To Get/Check the Size of the Priority Queue

It determines the size of a priority queue. In simple terms, the size() method is used to get the number of elements present in the Priority Queue.

Below is the C++ program to check the size of the priority queue:

C++




// C++ program to demonstrate the
// size() method of priority queue
#include <iostream>
#include <queue>
using namespace std;
 
// Driver code
int main()
{
  // create a priority queue of string
  priority_queue<string> pqueue;
 
  // add items to priority_queue
  pqueue.push("Geeks");
  pqueue.push("for");
  pqueue.push("Geeks");
  pqueue.push("C++");
 
  // get the size of queue
  int size = pqueue.size();
  cout << "Size of the queue: " << size;
 
  return 0;
}


Output

Size of the queue: 4

Refer end for complexity analysis.

5. To Swap Contents of a Priority Queue with Another of Similar Type

Swap() function is used to swap the contents of one priority queue with another priority queue of same type and same or different size.

Below is the C++ program to swap contents of a priority queue with another of similar type:

C++




// CPP program to illustrate
// Implementation of swap() function
 
#include <bits/stdc++.h>
using namespace std;
 
// Print elements of priority queue
void print(priority_queue<int> pq)
{
    while (!pq.empty()) {
        cout << pq.top() << " ";
        pq.pop();
    }
    cout << endl;
}
 
int main()
{
    // priority_queue container declaration
    priority_queue<int> pq1;
    priority_queue<int> pq2;
 
    // pushing elements into the 1st priority queue
    pq1.push(1);
    pq1.push(2);
    pq1.push(3);
    pq1.push(4);
 
    // pushing elements into the 2nd priority queue
    pq2.push(3);
    pq2.push(5);
    pq2.push(7);
    pq2.push(9);
 
    cout << "Before swapping:-" << endl;
    cout << "Priority Queue 1 = ";
    print(pq1);
    cout << "Priority Queue 2 = ";
    print(pq2);
 
    // using swap() function to swap elements of priority
    // queues
    pq1.swap(pq2);
 
    cout << endl << "After swapping:-" << endl;
    cout << "Priority Queue 1 = ";
    print(pq1);
    cout << "Priority Queue 2 = ";
    print(pq2);
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

Before swapping:-
Priority Queue 1 = 4 3 2 1 
Priority Queue 2 = 9 7 5 3 

After swapping:-
Priority Queue 1 = 9 7 5 3 
Priority Queue 2 = 4 3 2 1 

Refer end for complexity analysis.

6. To emplace a new element into the priority queue container

Emplace() function is used to insert a new element into the priority queue container, the new element is added to the priority queue according to its priority. It is similar to push operation. The difference is that emplace() operation saves unnecessary copy of the object.

Below is the C++ program to emplace a new element into the priority queue container:

C++




// CPP program to illustrate
// Implementation of emplace() function
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    priority_queue<int> pq;
    pq.emplace(1);
    pq.emplace(2);
    pq.emplace(3);
    pq.emplace(4);
    pq.emplace(5);
    pq.emplace(6);
    // Priority queue becomes 1, 2, 3, 4, 5, 6
 
    // Printing the priority queue
    cout << "Priority Queue = ";
    while (!pq.empty()) {
        cout << pq.top() << " ";
        pq.pop();
    }
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

Priority Queue = 6 5 4 3 2 1 

Refer end for complexity analysis.

7. To represent the type of object stored as an element in a priority_queue

The priority_queue :: value_type method is a built-in function in C++ STL which represents the type of object stored as an element in a priority_queue. It acts as a synonym for the template parameter.

Syntax: 

priority_queue::value_type variable_name

Below is the C++ program to represent the type of object stored as an element in a priority_queue:

C++




// C++ program to illustrate the
// priority_queue :: value_type function
 
#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    // declare integer value_type for priority queue
    priority_queue<int>::value_type AnInt;
 
    // declare string value_type for priority queue
    priority_queue<string>::value_type AString;
 
    // Declares priority_queues
    priority_queue<int> q1;
    priority_queue<string> q2;
 
    // Here AnInt acts as a variable of int data type
    AnInt = 20;
    cout << "The value_type is AnInt = " << AnInt << endl;
    q1.push(AnInt);
    AnInt = 30;
    q1.push(AnInt);
    cout << "Top element of the integer priority_queue is: "
         << q1.top() << endl;
 
    // here AString acts as a variable of string data type
    AString = "geek";
    cout << endl
         << "The value_type is AString = " << AString
         << endl;
    q2.push(AString);
    AString = "for";
    q2.push(AString);
    AString = "geeks";
    q2.push(AString);
 
    cout << "Top element of the string priority_queue is: "
         << q2.top() << endl;
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

The value_type is AnInt = 20
Top element of the integer priority_queue is: 30

The value_type is AString = geek
Top element of the string priority_queue is: geeks

Refer end for complexity analysis.

Complexities Of All The Operations:

Methods

Time Complexity

Auxiliary Space

priority_queue::empty()

O(1)

O(1)

priority_queue::size()

O(1)

O(1)

priority_queue::top()

O(1)

O(1)

priority_queue::push()

O(logN)

O(1)

priority_queue::pop()

O(logN)

O(1)

priority_queue::swap()

O(1)

O(N)

priority_queue::emplace()

O(logN)

O(1)

priority_queue value_type

O(1)

O(1)



Similar Reads

Queue in C++ Standard Template Library (STL)
Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its eleme
3 min read
Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
Binary Search in C++ Standard Template Library (STL)
Binary search is a widely used searching algorithm that requires the array to be sorted before search is applied. The main idea behind this algorithm is to keep dividing the array in half (divide and conquer) until the element is found, or all the elements are exhausted.It works by comparing the middle item of the array with our target, if it match
3 min read
Multimap in C++ Standard Template Library (STL)
Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap make it very much useful i
6 min read
Deque in C++ Standard Template Library (STL)
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basically an implementation of the data structure doub
4 min read
Pair in C++ Standard Template Library (STL)
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The pair container is a simple container defined in &lt;utility&gt; header consisting of two data elements or objects. The first element is referen
9 min read
List in C++ Standard Template Library (STL)
Lists are sequence containers that allow non-contiguous memory allocation. As compared to the vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick (constant time). Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward_list. std::
6 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the &lt;set&gt; header file. Syntax: std:
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference ob
2 min read
Multiset in C++ Standard Template Library (STL)
Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: begin() - Returns an iterator to the first element in the multiset --&gt; O(1)end() - Returns an iterator to the theoretical element that follows the last element in th
6 min read
Why can't a Priority Queue wrap around like an ordinary Queue?
Priority Queue: A priority queue is a special type of queue in which each element is assigned a priority value. And elements are served based on their priority. This means that elements with higher priority are served first. However, if elements with the same priority occur, they will be served in the order in which they were queued. A priority que
3 min read
Unordered Sets in C++ Standard Template Library
An unordered_set is an unordered associative container implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set take constant time O(1) on an average which can go up to linear time O(n) in the worst case which depends on the internally used hash
6 min read
C++ STL - Reverse Priority Queue
A priority Queue is an abstract data type that resembles a queue, and each element has a corresponding priority value. Priority queues are built on the top of the max heap and use an array or vector as an internal structure. In C++ STL, by default, the first element of the queue is the greatest of all elements in the queue and elements are in nonin
2 min read
Difference Between STL and Standard Library in C++
In C++, the term "Standard Library" and "Standard Template Library" are often misinterpreted as the same. Although they sound same with only a single word difference, they refer to the different part of the C++ programming language. In this article, we will learn what's the difference between the C++ Standard Library and Standard Template Library (
3 min read
queue::empty() and queue::size() in C++ STL
Queue is a type of container adaptor that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::empty() empty() function is used to check if the queue container is empty or not. SyntaxqueueName.empty()ParametersThis function does not accept any parameter.Return Val
4 min read
queue::front() and queue::back() in C++ STL
Queue are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::front() This function is used to reference the first or the oldest element of the queue container. This function can be used to fetch the first element of a queue.Syn
3 min read
Priority queue of pairs in C++ (Ordered by first)
In C++, priority_queue implements heap. Below are some examples of creating priority queue of pair type. Max Priority queue (Or Max heap) ordered by first element // C++ program to create a priority queue of pairs. // By default a max heap is created ordered // by first element of pair. #include &lt;bits/stdc++.h&gt; using namespace std; // Driver
2 min read
Priority Queue of Maps in C++ with Examples
Priority Queue Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in non-increasing order (hence we can see that each element of the queue has a priority {fixed order}). Generally, priority queues are of two types: max-heap an
15+ min read
Find the K closest points to origin using Priority Queue
Given a list of n points on 2D plane, the task is to find the K (k &lt; n) closest points to the origin O(0, 0). Note: The distance between a point P(x, y) and O(0, 0) using the standard Euclidean Distance. Examples: Input: [(1, 0), (2, 1), (3, 6), (-5, 2), (1, -4)], K = 3 Output: [(1, 0), (2, 1), (1, -4)] Explanation: Square of Distances of points
7 min read
Efficient way to initialize a priority queue
STL Priority Queue is the implementation of Heap Data Structure. By default, it's a max heap, and can be easily for primitive data types. There are some important applications of it which can be found in this article. Priority queue can be initialized in two ways either by pushing all elements one by one or by initializing using their constructor.
7 min read
Indexed Priority Queue with Implementation
Priority queue is a data structure in which data is stored on basis of its priority. In an Indexed Priority Queue, data is stored just like standard priority queue and along with this, the value of a data can be updated using its key. It is called "indexed" because a hash map can be used to store the index in container using the key of key-value pa
8 min read
Priority Queue of Lists in C++ with Examples
Priority Queue Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}). Functions used with Priority Queue: empty(): This functio
5 min read
Priority Queue of Sets in C++ with Examples
Priority Queues Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}). Functions used with Priority Queues: empty(): Returns wh
4 min read
Priority Queue of Tuples in C++ with Examples
Priority Queue Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}). Functions associated with a Priority Queue: empty(): This
13 min read
Priority queue of pairs in C++ with ordering by first and second element
Priority Queue: Priority queue is the extension of the queue in which elements associated with priority and elements having higher priority is popped first. Priority queue can contain elements with various data types such as integer, pair of integers, custom data type. But one thing is common that there is one element that defines the priority of t
5 min read
Multiple comparisons in a C++ priority queue?
What is a Priority Queue? A Priority Queue is an abstract data type that is similar to a queue, and every element has some priority value associated with it. The priority of the elements in a priority queue determines the order in which elements are served (i.e., the order in which they are removed). If in any case, the elements have the same prior
5 min read
Implement the insert and delete functions on Priority queue without Array
A priority Queue is a type of queue in which every element is associated with a priority and is served according to its priority. We will use two popular data structures for implementing priority queues without arrays - Fibonacci HeapBinomial HeapFibonacci Heap:Fibonacci heap is a heap data structure that is composed of a collection of min-heap-ord
15+ min read
Priority Queue using Binary Heap
Priority Queue is an extension of the queue with the following properties:   Every item has a priority associated with it.An element with high priority is dequeued before an element with low priority.If two elements have the same priority, they are served according to their order in the queue.A Binary Heap is a Binary Tree with the following proper
15+ min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Find element in rangestd :: find_if_not : Find elemen
4 min read
Practice Tags :