how to use comparitor in priority queu in c++
To use a comparator in a priority queue in C++, you need to define a comparison function or overload the comparison operator (<
) for the elements you want to store in the priority queue. Here are the steps to do it:
- Define a comparison function or overload the comparison operator (
<
) for the elements you want to store in the priority queue. The comparison function should take two parameters of the same type as the elements and return a boolean value indicating whether the first element should be considered "less than" the second element.
Here's an example of a comparison function:
cpp
bool compare(int a, int b) {
return a > b; // Priority queue with elements in descending order
}
And here's an example of overloading the comparison operator: ```cpp struct MyStruct { int value;
bool operator<(const MyStruct& other) const {
return value > other.value; // Priority queue with elements in descending order
}
}; ```
- Create a priority queue object and specify the comparison function or operator as the second template argument.
cpp std::priority_queue<int, std::vector<int>, decltype(&compare)> pq(compare);
or
cpp
std::priority_queue<MyStruct> pq;
Note that in the second example, the comparison function or operator is already defined within the MyStruct
struct.
Add elements to the priority queue using the
push()
member function.cpp pq.push(10); pq.push(5); pq.push(20);
Access the top element of the priority queue using the
top()
member function.cpp int topElement = pq.top();
Note that the top element will be the element that is considered the highest priority according to the comparison function or operator.
- Remove the top element from the priority queue using the
pop()
member function.cpp pq.pop();
After pop()
, the next highest priority element will become the new top element.
That's it! You have now used a comparator in a priority queue in C++. The priority queue will automatically maintain the order of the elements based on the comparison function or operator you provided.