1#include<queue>
2std::priority_queue <int, std::vector<int>, std::greater<int> > minHeap;
1This is frequently used in Competitive Programming.
2We first multiply all elements with (-1). Then we create a max heap (max heap is the default for priority queue).
3When we access the data and want to print it we simply multiply those elements with (-1) again.
1int arr[]={1,2,1,3,3,5,7};
2 PriorityQueue<Integer> a=new PriorityQueue<>();
3 for(int i:arr){
4 a.add(i);
5 }
6 while(!a.isEmpty())
7 System.out.println(a.poll());
1#include <bits/stdc++.h>
2using namespace std;
3
4// User defined class, Point
5class Point
6{
7 int x;
8 int y;
9public:
10 Point(int _x, int _y)
11 {
12 x = _x;
13 y = _y;
14 }
15 int getX() const { return x; }
16 int getY() const { return y; }
17};
18
19// To compare two points
20class myComparator
21{
22public:
23 int operator() (const Point& p1, const Point& p2)
24 {
25 return p1.getX() > p2.getX();
26 }
27};
28
29// Driver code
30int main ()
31{
32 // Creates a Min heap of points (order by x coordinate)
33 priority_queue <Point, vector<Point>, myComparator > pq;
34
35 // Insert points into the min heap
36 pq.push(Point(10, 2));
37 pq.push(Point(2, 1));
38 pq.push(Point(1, 5));
39
40 // One by one extract items from min heap
41 while (pq.empty() == false)
42 {
43 Point p = pq.top();
44 cout << "(" << p.getX() << ", " << p.getY() << ")";
45 cout << endl;
46 pq.pop();
47 }
48
49 return 0;
50}
1#include <bits/stdc++.h>
2using namespace std;
3
4
5int main ()
6{
7
8 priority_queue <int> pq;
9 pq.push(5);
10 pq.push(1);
11 pq.push(10);
12 pq.push(30);
13 pq.push(20);
14
15
16 while (pq.empty() == false)
17 {
18 cout << pq.top() << " ";
19 pq.pop();
20 }
21
22 return 0;
23}