max heap c++ priority queue code example
Example 1: priority queue max heap in java
//Sol1
PriorityQueue queue = new PriorityQueue<>(10, Collections.reverseOrder());
//Sol2
// PriorityQueue pq = new PriorityQueue<>((x, y) -> y - x);
PriorityQueue pq =new PriorityQueue<>((x, y) -> Integer.compare(y, x));
//Sol3
PriorityQueue pq = new PriorityQueue(defaultSize, new Comparator() {
public int compare(Integer lhs, Integer rhs) {
if (lhs < rhs) return +1;
if (lhs.equals(rhs)) return 0;
return -1;
}
});
Example 2: Priority Queue using Min Heap in c++
#include
using namespace std;
int main ()
{
priority_queue pq;
pq.push(5);
pq.push(1);
pq.push(10);
pq.push(30);
pq.push(20);
while (pq.empty() == false)
{
cout << pq.top() << " ";
pq.pop();
}
return 0;
}