C++ STL Tutorial - Priority Queue
Priority Queue is a container in the C++ STL library, which is implemented using Heap data structure. It is used to maintain a sorted list of elements, with the highest priority element at the front of the queue.
Syntax
#include <queue>
using namespace std;
priority_queue <int> pq;
Example
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<int> pq;
pq.push(10);
pq.push(20);
pq.push(15);
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
Output
20 15 10
Explanation
In the above example, we have created a priority queue using the priority_queue
template class. We then insert three elements into the queue using the push()
function.
To retrieve the elements in sorted order, we use a loop that runs until the priority queue is empty. For each element, we use the top()
function to get the highest priority element and then remove it from the queue using the pop()
function.
Use
Priority Queue is useful in situations where we need to maintain a sorted list of elements, with the highest priority element at the front. Some applications of the Priority Queue are:
- Implementing Dijkstra's Algorithm for shortest path finding
- Implementing Huffman Coding for data compression
- Implementing Prim's Algorithm for Minimum Spanning Tree
Important Points
- Priority Queue is a container that uses Heap data structure.
- The highest priority element is always at the front of the queue.
- Priority Queue is useful when we need to maintain a sorted list of elements with the highest priority element at the front.
- The
push()
function is used to insert elements into the queue. - The
pop()
function is used to remove the highest priority element from the queue. - The
top()
function is used to retrieve the highest priority element from the queue.
Summary
Priority Queue is a container in the C++ STL library, which is used to maintain a sorted list of elements, with the highest priority element at the front. It is implemented using Heap data structure. Priority Queue is useful in situations where we need to maintain a sorted list of elements with the highest priority element at the front.