Heaps and Priority Queues in C++
...

Heaps
...

A heap is a specialized tree-based data structure that satisfies the heap property - the value of each node is greater than or equal to (or less than or equal to) the values of its children.

There are two common types of heaps:

  • Max heap - Parent nodes are greater than or equal to children
  • Min heap - Parent nodes are less than or equal to children

Heaps are typically implemented using arrays, where:

  • The root element is at array
  • For any node at array :
    • Its left child is at array
    • Its right child is at array

Heaps are useful for implementing priority queues, as they allow efficient retrieval and removal of the maximum/minimum element.

Heap Functions in C++
...

C++ provides several heap functions in the <algorithm> header:

  • make_heap - Creates a heap from an array
  • push_heap - Adds an element to a heap
  • pop_heap - Removes the largest/smallest element from a heap
#include <algorithm> 

// Create a max heap
std::vector<int> vec = {3, 1, 4, 1, 5, 9};
std::make_heap(vec.begin(), vec.end()); 

// Add element
vec.push_back(2);
std::push_heap(vec.begin(), vec.end());

// Remove largest element
std::pop_heap(vec.begin(), vec.end());
vec.pop_back(); 

The heap functions allow manipulating a heap stored in a vector or array efficiently.

Priority Queues
...

A priority queue is an abstract data type that provides 3 main operations:

  • Insert - Add an element
  • GetMax/GetMin - Retrieve the maximum/minimum element
  • ExtractMax/ExtractMin - Remove and return the maximum/minimum element

Priority queues maintain elements in order of priority. They are commonly implemented using heaps, as heaps provide efficient O(log n) operations for insertion and extraction of max/min.

In C++, std::priority_queue provides a priority queue implementation using heaps.

#include <queue>

std::priority_queue<int> pq; 

// Insert elements
pq.push(3); 
pq.push(1);
pq.push(5);

// Get min element
int min = pq.top(); 

// Remove min element
pq.pop();

Comparison
...

  • Heaps are a data structure that can be used to build a priority queue.
  • std::priority_queue in C++ provides a priority queue implementation using heaps.
  • The heap functions allow direct manipulation of heaps stored in arrays/vectors.
  • Priority queues provide an abstract interface with insertion, extraction and peek operations.

So heaps give lower level control, while priority queues provide a convenient abstraction. Priority queues are usually preferred unless direct manipulation of a heap is required.

The time complexities of heap operations and priority queue operations are the same - O(log n) for insertion and extraction.

Overall, priority queues provide a more flexible and user-friendly interface for ordered element access. But heaps allow direct manipulation when the raw structure is needed.