techmore.in

C++ Priority Queues

Priority queues in C++ are data structures that allow you to efficiently retrieve the element with the highest (or lowest) priority. The standard library provides a priority_queue container adapter that is built on top of a heap. By default, it implements a max-heap, where the largest element has the highest priority.

Here's a quick overview of how to use std::priority_queue:

Basic Usage

  1. Include the necessary headers:

    cpp
    #include #include
  2. Create a priority_queue:

    By default, it uses a max-heap (largest element has the highest priority).

    cpp
    std::priority_queue<int> pq;
  3. Add elements to the priority queue:

    cpp
    pq.push(10); pq.push(20); pq.push(15);
  4. Access the top element (highest priority):

    cpp
    std::cout << "Top element: " << pq.top() << std::endl; // Outputs 20
  5. Remove the top element:

    cpp
    pq.pop();
  6. Check if the priority queue is empty:

    cpp
    if (pq.empty()) { std::cout << "Priority queue is empty." << std::endl; }

Custom Comparator

You can also use a custom comparator to change the behavior of the priority queue. For example, to create a min-heap (where the smallest element has the highest priority), you can use the following approach:

  1. Include the necessary headers:

    cpp
    #include #include #include
  2. Define a custom comparator:

    cpp
    struct Compare { bool operator()(int a, int b) { return a > b; // Min-heap (smallest element has the highest priority) } };
  3. Create a priority queue with the custom comparator:

    cpp
    std::priority_queue<int, std::vector<int>, Compare> pq;
  4. Add elements and use the priority queue as before:

    cpp
    pq.push(10); pq.push(20); pq.push(15); std::cout << "Top element: " << pq.top() << std::endl; // Outputs 10

Example Code

Here's a complete example demonstrating both the default max-heap and a custom min-heap:

cpp
#include #include #include // Custom comparator for a min-heap struct Compare { bool operator()(int a, int b) { return a > b; // Min-heap } }; int main() { // Default max-heap std::priority_queue<int> maxHeap; maxHeap.push(10); maxHeap.push(20); maxHeap.push(15); std::cout << "Max-Heap:" << std::endl; while (!maxHeap.empty()) { std::cout << maxHeap.top() << " "; maxHeap.pop(); } std::cout << std::endl; // Custom min-heap std::priority_queue<int, std::vector<int>, Compare> minHeap; minHeap.push(10); minHeap.push(20); minHeap.push(15); std::cout << "Min-Heap:" << std::endl; while (!minHeap.empty()) { std::cout << minHeap.top() << " "; minHeap.pop(); } std::cout << std::endl; return 0; }

This code will output:

makefile
Max-Heap: 20 15 10 Min-Heap: 10 15 20

Feel free to adjust the example based on your specific needs!