Priority Queue
Priority Queue in C++
IntermediateTopic: STL Containers Programs
C++ Priority Queue Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
// Max heap (default - largest element at top)
priority_queue<int> pq;
pq.push(30);
pq.push(10);
pq.push(50);
pq.push(20);
pq.push(40);
cout << "Priority Queue (Max Heap):" << endl;
cout << "Top element (maximum): " << pq.top() << endl;
cout << "\nElements in descending order:" << endl;
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
// Min heap
priority_queue<int, vector<int>, greater<int>> minHeap;
minHeap.push(30);
minHeap.push(10);
minHeap.push(50);
minHeap.push(20);
minHeap.push(40);
cout << "\nPriority Queue (Min Heap):" << endl;
cout << "Top element (minimum): " << minHeap.top() << endl;
cout << "\nElements in ascending order:" << endl;
while (!minHeap.empty()) {
cout << minHeap.top() << " ";
minHeap.pop();
}
cout << endl;
// Custom comparator
auto cmp = [](int a, int b) { return a > b; };
priority_queue<int, vector<int>, decltype(cmp)> customPQ(cmp);
customPQ.push(5);
customPQ.push(2);
customPQ.push(8);
cout << "\nCustom Priority Queue:" << endl;
while (!customPQ.empty()) {
cout << customPQ.top() << " ";
customPQ.pop();
}
cout << endl;
return 0;
}Output
Priority Queue (Max Heap): Top element (maximum): 50 Elements in descending order: 50 40 30 20 10 Priority Queue (Min Heap): Top element (minimum): 10 Elements in ascending order: 10 20 30 40 50 Custom Priority Queue: 2 5 8
Understanding Priority Queue
Priority queue is a container that provides constant-time access to the largest (or smallest) element. By default, it's a max heap. Operations: push(), pop(), top(), empty(), size(). For min heap, use greater<int> comparator. Common uses: 1) Dijkstra's algorithm, 2) Heap sort, 3) Task scheduling by priority, 4) Finding k largest/smallest elements. Implemented as a binary heap with O(log n) insert/delete.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.