std::priority_queue is a container adapter that stores and manages elements based on their priority. By default, it uses a max-heap, where the largest element has the highest priority.
- It uses a heap internally and provides efficient access to the highest-priority element.
- A custom comparator can change the priority order and create structures such as a min-heap.
#include <iostream>
#include <queue>
using namespace std;
int main(){
// Create a max-heap priority queue (default)
priority_queue<int> pq;
pq.push(30);
pq.push(10);
pq.push(20);
pq.push(40);
cout << "Elements removed from priority queue in order:\n";
while (!pq.empty()){
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
Output
Elements removed from priority queue in order: 40 30 20 10
Explanation: The code creates a max-heap priority queue and inserts four elements. The top() function always returns the largest element, so the elements are removed in descending order of their values.
Syntax
Priority queue is defined as std::priority_queue inside <queue> header file.
priority_queue<T, Container, Compare> pq;
where:
- T: Data type of the elements.
- Container: Underlying container used to store the elements. It is vector<T> by default.
- Compare: Comparison function or function object that determines the priority order. It is optional.
- pq: Name of the priority queue.
Declaration and Initialization
A priority queue can be declared as a max-heap or min-heap depending on the required ordering.
Max-Heap: A max-heap is the default behavior, where the largest element has the highest priority.
priority_queue<int>pq;
Min-Heap: A min-heap gives the smallest element the highest priority. It can be created using greater<T>.
priority_queue<int, vector<int>, greater<int>> pq;
Initialization means adding elements to it so it can manage them based on their priority.
pq.push(10);
pq.push(5);
pq.push(20);
Basic Operations
The commonly used operations on a priority queue are discussed below.
1. Inserting Elements
The push() function inserts an element into the priority queue and maintains the heap according to the priority order. The time complexity of push() is O(log n).
- In a max-heap, the largest element gets the highest priority.
- In a min-heap, the smallest element gets the highest priority.
#include <iostream>
#include <queue>
using namespace std;
int main(){
priority_queue<int> pq;
// Inserting elements
pq.push(9);
pq.push(8);
pq.push(6);
return 0;
}
Explanation: This code creates a max-heap priority queue and inserts 9, 8, and 6 using push(). The priority queue automatically maintains the heap property after each insertion.
2. Accessing the Top Element
The top() function returns the element with the highest priority. The time complexity of top() is O(1).
- In a max-heap, it returns the largest element.
- In a min-heap, it returns the smallest element.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> pq;
// Insert elements into the priority queue
pq.push(9);
pq.push(8);
pq.push(6);
// Access the highest-priority element
cout << pq.top();
return 0;
}
Output
9
Explanation: The priority queue is a max-heap, so 9 has the highest priority among the inserted elements. Therefore, top() returns 9.
3. Deleting Elements
The pop() function removes the element with the highest priority from the priority queue. The time complexity of pop() is O(log n).
- Only the top element can be removed directly.
- After removal, the heap is rearranged to maintain the priority order.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> pq;
// Insert elements into the priority queue
pq.push(9);
pq.push(8);
pq.push(6);
// Remove the highest-priority element
pq.pop();
// Access the new top element
cout << pq.top();
return 0;
}
Output
8
Explanation: The pop() function removes 9, which is the highest-priority element in the max-heap. After removal, 8 becomes the new top element.
4. Checking if Priority Queue is Empty
The empty() function checks whether the priority queue contains any elements. The time complexity is O(1).
- Returns true if the priority queue is empty.
- Returns false if it contains one or more elements.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> pq;
// Check whether the priority queue is empty
if (pq.empty())
cout << "Priority queue is empty." << endl;
// Insert elements into the priority queue
pq.push(50);
pq.push(30);
// Check whether the priority queue contains elements
if (!pq.empty())
cout << "Priority queue is not empty. Top element: "
<< pq.top() << endl;
return 0;
}
Output
Priority queue is empty. Priority queue is not empty. Top element: 50
Explanation: The code first checks an empty priority queue using empty(). After inserting two elements, the second check confirms that the priority queue is no longer empty.
5. Finding the Size of Priority Queue
The size() function returns the number of elements currently stored in the priority queue. It does not modify the priority queue and the time complexity is O(1).
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> pq;
// Insert elements into the priority queue
pq.push(100);
pq.push(50);
// Display the current size
cout << "Size of priority queue: "
<< pq.size() << endl;
// Remove the top element
pq.pop();
// Display the updated size
cout << "Size after one pop: "
<< pq.size() << endl;
return 0;
}
Output
Size of priority queue: 2 Size after one pop: 1
Explanation: The priority queue initially contains two elements, so size() returns 2. After removing one element using pop(), the size becomes 1.
Traversing a Priority Queue
A priority_queue does not provide iterators, so its elements cannot be directly traversed. To inspect all elements without modifying the original priority queue, create a copy and repeatedly access and remove its top element.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> pq;
// Insert elements into the priority queue
pq.push(9);
pq.push(8);
pq.push(6);
// Create a copy of the priority queue
priority_queue<int> temp(pq);
// Traverse the copied priority queue
while (!temp.empty())
{
cout << temp.top() << " ";
temp.pop();
}
return 0;
}
Output
9 8 6
Explanation: The code creates a copy of the priority queue and repeatedly accesses and removes its top element. This prints the elements in priority order while keeping the original priority queue unchanged.
Changing the Priority Order
By default, priority_queue is a max-heap. The priority order can be changed by providing a custom comparator. For example, greater<int> can be used to create a min-heap where the smallest element has the highest priority.
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
using namespace std;
int main()
{
// Create a min-heap priority queue
priority_queue<int, vector<int>, greater<int>> pq;
// Insert elements into the priority queue
pq.push(9);
pq.push(8);
pq.push(6);
// Remove elements in ascending order
while (!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
Output
6 8 9
Explanation: The greater<int> comparator changes the priority order so that the smallest element is placed at the top. The elements are therefore removed in ascending order. The vector argument is specified because Compare is the third template parameter of priority_queue.
Priority Queue vs Queue
Feature | Queue | Priority Queue |
|---|---|---|
Order of Removal | FIFO (First-In, First-Out) | Based on priority |
Element Priority | All elements treated equally. | Each element has a priority. |
Use case | Task scheduling, print queue | CPU scheduling, Dijkstra's Algorithm |
Default Behavior | Inserts at rear, removes front | Inserts anywhere, removes highest priority |
STL Class in C++ | queue | priority_queue |
Member Functions of std::priority_queue
Following is the list of all member functions of std::priority_queue class in C++:
Function | Definition |
|---|---|
| empty() | Returns whether the priority queue is empty. |
| size()Â | Returns the size of the priority queue. |
| top() | Returns top element of the priority queue |
| push()Â | Adds the element into the priority queue. |
| pop() | Deletes the top element of the priority queue. |
| swap() | Used to swap the contents of two priority queues provided the queues must be of the same type, although sizes may differ. |
| emplace() | Used to insert a new element into the priority queue container. |