Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::priority_queue

Explanation

Largest element always on top. Uses std::vector internally.

See std::priority_queue.

Time complexity:

OperationComplexity
push()O(log n)
pop()O(log n)
empty(), size()O(1)

std::priority_queue is implemented as a binary heap.

Code

#include <print>
#include <queue>

int main() {
  std::priority_queue<int, std::vector<int>, std::less<int>> maxHeap;

  maxHeap.push(0x2000);
  maxHeap.push(0x3000);
  maxHeap.push(0x1000);

  while (!maxHeap.empty()) {
    std::println("Process: {:#x}", maxHeap.top());
    maxHeap.pop();
  }

  return 0;
}

View on GitHub.

Output

$ ./src/data-structures/build/std-priority_queue
Process: 0x3000
Process: 0x2000
Process: 0x1000