A priority queue is a dynamically resizing container adapter in the C++ Standard Library. Elements in a priority queue are arranged in non-decreasing order such that the first element is always the greatest element in the queue.
Below are the constructors for a priority queue:
1. Empty priority queue
priority_queue<data_type> name;
2. Constructor with range input
priority_queue<data_type> name(iterator_begin,iterator_end);
The range includes all the elements between iterator_begin
and iterator_end
, including the element pointed by iterator_begin
but not the element pointed by iterator_end
3. Constructor with comparison and container objects
priority_queue<data_type, container_object, comparison_object> name //after name, the container can be initialized empty or with a range input
The parameter comparison is used to order the heap. It may be a function pointer or function object capable of comparisons and must have two arguments.
The container object is by default a vector.
Example:
#include <queue> #include <iostream> using namespace std; int main() { priority_queue<int> q1; //empty int arr[]= {1,2,3,4,5}; priority_queue<int> q2(arr,arr+5); //range constructor cout<<"Q2: "<<endl; while (!q2.empty()) { cout<<q2.top()<<" "; q2.pop(); } cout<<endl; priority_queue<int, vector<int>, greater<int> > q3; q3.push(3); q3.push(5); q3.push(1); cout<<"Q3: "<<endl; while (!q3.empty()) { cout<<q3.top()<<" "; q3.pop(); } return 0; }
Output:
Q2: 5 4 3 2 1 Q3: 1 3 5
Here are various methods associated with priority queues in the C++ Standard Library
priority_queue::empty
: Test whether priority queue is emptypriority_queue::size
: Return number of elements in the containerpriority_queue::top
: Access the top i.e. first elementpriority_queue::push
: Insert elementpriority_queue::pop
: Remove the top elementpriority_queue::emplace
: Construct and insert elementpriority_queue::swap
: Swap contents of two containers
Example:
#include <queue> #include <iostream> using namespace std; void printq(priority_queue<int> q) { while (!q.empty()) //using empty { cout<<q.top()<<" "; //accessing top element q.pop(); //removing top element } } int main() { priority_queue<int> q; q.push(1); //pushing values q.push(8); q.push(7); q.push(3); q.push(2); cout<<"Size of Q: "<<q.size()<<endl; //size cout<<"Q: "<<endl; printq(q); priority_queue<int> r; r.emplace(1); r.emplace(2); r.emplace(3); cout<<"\nR: \n"; printq(r); q.swap(r); cout<<"\nQ: "<<endl; printq(q); cout<<"\nR: "<<endl; printq(r); return 0; }
Output:
Size of Q: 5 Q: 8 7 3 2 1 R: 3 2 1 Q: 3 2 1 R: 8 7 3 2 1