how to use comparator funtion in priority queue in c++

To use a comparator function in a priority queue in C++, follow these steps:

  1. Include the necessary header file: Begin by including the <queue> header file, which contains the definition of the priority_queue class.

  2. Define the comparator function: Next, define a comparator function that compares two elements and returns true if the first element is considered to have a higher priority than the second element. The comparator function should be a binary function that takes two arguments of the same type as the elements in the priority queue and returns a bool.

  3. Declare the priority queue with the comparator function: Declare a priority queue object, specifying the element type and the comparator function as template arguments. For example, if you have a priority queue of integers and your comparator function is named compare, you would declare the priority queue as follows: priority_queue<int, vector<int>, compare> pq;

  4. Use the priority queue: You can now use the priority queue to insert elements and retrieve the highest-priority element. When inserting elements, the priority queue will use the comparator function to determine their order.

Here is an example that demonstrates the usage of a comparator function in a priority queue in C++:

#include <iostream>
#include <queue>
#include <vector>

// Comparator function
bool compare(int a, int b) {
    // Higher value has higher priority
    return a > b;
}

int main() {
    // Declare priority queue with the comparator function
    std::priority_queue<int, std::vector<int>, decltype(compare)*> pq(compare);

    // Insert elements
    pq.push(5);
    pq.push(2);
    pq.push(10);

    // Retrieve highest-priority element
    int highestPriority = pq.top();
    std::cout << "Highest priority element: " << highestPriority << std::endl;

    return 0;
}

In this example, the comparator function compare is defined to compare two integers and return true if the first integer has a higher value than the second integer. The priority queue is declared with the comparator function compare, and elements are inserted into the priority queue using the push function. The highest-priority element is retrieved using the top function, and its value is printed to the console.

I hope this explanation helps! Let me know if you have any further questions.