1/* A priority queue maintains a set of elements. The supported operations are
2insertion and, depending on the type of the queue, retrieval and removal
3of either the minimum or maximum element. Insertion and removal take
4O(logn) time, and retrieval takes O(1) time. */
5priority_queue<int> q;
6q.push(3); // 3
7q.push(5); // 3 5
8q.push(7); // 3 5 7
9q.push(2); // 2 3 5 7
10cout << q.top() << "\n"; // 7
11q.pop();
12cout << q.top() << "\n"; // 5
13q.pop();
14q.push(6);
15cout << q.top() << "\n"; // 6
16q.pop();
1// using GCC 10.2 (C++2a) compiler
2#include <functional>
3#include <queue>
4#include <vector>
5#include <iostream>
6
7template<typename T> void print_queue(T& q) {
8 while(!q.empty()) {
9 std::cout << q.top() << " ";
10 q.pop();
11 }
12 std::cout << '\n';
13}
14
15int main() {
16 std::priority_queue<int> q;
17
18 for(int n : {1,8,5,6,3,4,0,9,7,2})
19 q.push(n);
20
21 print_queue(q);
22
23 std::priority_queue<int, std::vector<int>, std::greater<int> > q2;
24
25 for(int n : {1,8,5,6,3,4,0,9,7,2})
26 q2.push(n);
27
28 print_queue(q2);
29
30 // Using lambda to compare elements.
31 auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); };
32 std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);
33
34 for(int n : {1,8,5,6,3,4,0,9,7,2})
35 q3.push(n);
36
37 print_queue(q3);
38
39}
40
1// Implementation of priority_queue in c++
2
3//queue with elements in decreasing order
4priority_queue<int> pq;
5
6// queue with elements in increasing order using compare function inside declaration
7priority_queue <int, vector<int>, greater<int> > pq;
8
9//priority_queue of type pair<int, int>
10#define pp pair<int, int>
11priority_queue <pp, vector<pp>, greater<pp> > pq;
12
1//Shubh'grepper
2// Implementation of priority_queue in c++
3
4//queue with elements in decreasing order
5priority_queue<int> pq;
6
7// queue with elements in increasing order using compare function inside declaration
8priority_queue <int, vector<int>, greater<int> > pq;
9
10//priority_queue of type pair<int, int>
11#define pp pair<int, int>
12priority_queue <pp, vector<pp>, greater<pp> > pq;
13
1#include<iostream>
2#include<queue>
3#include<algorithm>
4
5using namespace std;
6
7int main()
8{
9 priority_queue<int>pq;
10 int n=5;
11 while(n--)
12 {
13 int val;
14 cout<<"enter the value you want to insert:"<<endl;
15 cin>>val;
16 pq.push(val);
17 }
18 priority_queue<int>p;
19 p.push(100);
20 p.push(1000);
21 p.push(3000);
22 p.push(5000);
23 pq.swap(p);
24 while(!pq.empty())
25 {
26 cout<<pq.top()<<" ";
27 pq.pop();
28 }
29 return 0;
30}
31
1/* Program to access an element of highest priority */
2
3#include<iostream>
4#include<queue> //Header-file for queue
5using namespace std;
6
7
8int main()
9{
10priority_queue<int> p1;
11p1.push(35);
12p1.push(40);
13p1.push(95);
14p1.push(25);
15
16cout<<p1.top(); //fetch element of highest
17priority(maximum element) i.e 95
18}
19