std::priority_queue

A max-heap by default

#include <functional>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

int main() {
    priority_queue<int> maxHeap;               // biggest on top
    for (int x : {5, 1, 8, 3}) maxHeap.push(x);
    while (!maxHeap.empty()) {
        cout << maxHeap.top() << ' ';
        maxHeap.pop();
    }
    cout << endl;

    priority_queue<int, vector<int>, greater<int>> minHeap;   // smallest on top
    for (int x : {5, 1, 8, 3}) minHeap.push(x);
    while (!minHeap.empty()) {
        cout << minHeap.top() << ' ';
        minHeap.pop();
    }
    cout << endl;
    return 0;
}

Output

8 5 3 1 
1 3 5 8 

priority_queue<int, vector<int>, greater<int>> is long to type but just means “a min-heap of ints”.

Priorities with pairs

Pairs compare by first, then second. In a min-heap of (priority, name), priority 1 comes out first:

#include <functional>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;

int main() {
    priority_queue<pair<int, string>, vector<pair<int, string>>, greater<pair<int, string>>> er;
    er.push({3, "sprained ankle"});
    er.push({1, "heart attack"});
    er.push({2, "broken arm"});
    er.push({1, "breathing problem"});
    while (!er.empty()) {
        cout << er.top().first << " " << er.top().second << endl;
        er.pop();
    }
    return 0;
}

Output

1 breathing problem
1 heart attack
2 broken arm
3 sprained ankle
OperationHeapSorted vectorUnsorted vector
addO(log n)O(n)O(1)
take the topO(log n)O(1)O(n)
HOME LABS COMMUNITY DASHBOARD