Example 1: priority queue c++
/* A priority queue maintains a set of elements. The supported operations are
insertion and, depending on the type of the queue, retrieval and removal
of either the minimum or maximum element. Insertion and removal take
O(logn) time, and retrieval takes O(1) time. */
priority_queue q;
q.push(3); // 3
q.push(5); // 3 5
q.push(7); // 3 5 7
q.push(2); // 2 3 5 7
cout << q.top() << "\n"; // 7
q.pop();
cout << q.top() << "\n"; // 5
q.pop();
q.push(6);
cout << q.top() << "\n"; // 6
q.pop();
Example 2: implemetation of priority queue in c++
// Implementation of priority_queue in c++
//queue with elements in decreasing order
priority_queue pq;
// queue with elements in increasing order using compare function inside declaration
priority_queue , greater > pq;
//priority_queue of type pair
#define pp pair
priority_queue , greater > pq;
Example 3: priority queue cpp
// using GCC 10.2 (C++2a) compiler
#include
#include
#include
#include
template void print_queue(T& q) {
while(!q.empty()) {
std::cout << q.top() << " ";
q.pop();
}
std::cout << '\n';
}
int main() {
std::priority_queue q;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q.push(n);
print_queue(q);
std::priority_queue, std::greater > q2;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q2.push(n);
print_queue(q2);
// Using lambda to compare elements.
auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); };
std::priority_queue, decltype(cmp)> q3(cmp);
for(int n : {1,8,5,6,3,4,0,9,7,2})
q3.push(n);
print_queue(q3);
}
Example 4: priority queue in c++
//Shubh'grepper
// Implementation of priority_queue in c++
//queue with elements in decreasing order
priority_queue pq;
// queue with elements in increasing order using compare function inside declaration
priority_queue , greater > pq;
//priority_queue of type pair
#define pp pair
priority_queue , greater > pq;