Priority Queue in C++
Level 5353 keystrokes
priority_queue is a max-heap by default, so top() is always the largest element; popping everything prints 50 30 20 10. With greater<int> it becomes a min-heap whose top() is the smallest value.
C++ code
// By default the largest element has the highest priority (max-heap)1priority_queue<int> maxHeap;// Inserts in any order; the heap keeps the largest on top2maxHeap.push(30);3maxHeap.push(10);4maxHeap.push(50);5maxHeap.push(20);6 7cout << "Max heap:" << endl;// Repeats until the queue is empty8while (!maxHeap.empty()) { // top() reads the largest remaining element9 cout << maxHeap.top() << " "; // pop() removes it (it returns nothing)10 maxHeap.pop();11}// Ends the line 50 30 20 1012cout << endl;13 // greater<int> as the comparator turns it into a min-heap14priority_queue<int, vector<int>, greater<int>> minHeap;15minHeap.push(30);16minHeap.push(10);// The smallest value is on top: prints "Min: 10"17cout << "Min: " << minHeap.top() << endl;Output
Max heap: 50 30 20 10 Min: 10
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
<× 20;× 13(× 11)× 11.× 10"× 6>× 4_× 2,× 2:× 2