C++ - Priority Queue top() Function
The C++ priority_queue::top function is used to return a reference to the top element of the priority_queue. priority_queue is similar to a heap, where elements can be inserted in any order and max heap element is retrieved first. Hence, The first element of the priority_queue will be the max heap element.
Syntax
const value_type& top() const;
const_reference top() const;
Parameters
No parameter is required.
Return Value
A reference to the top element in the priority_queue.
Time Complexity
Constant i.e, Θ(1).
Example:
In the below example, the priority_queue::top function is used to access the top element of the priority_queue called p_queue.
#include <iostream> #include <queue> using namespace std; int main (){ priority_queue<int> p_queue; //add new elements in the priority_queue p_queue.push(100); p_queue.push(80); p_queue.push(990); p_queue.push(85); p_queue.push(10); cout<<"The top element of p_queue is: "; cout<<p_queue.top(); cout<<"\n\nDelete the top element of the p_queue.\n\n"; p_queue.pop(); cout<<"Now, The top element of p_queue is: "; cout<<p_queue.top(); return 0; }
The output of the above code will be:
The top element of p_queue is: 990 Delete the top element of the p_queue. Now, The top element of p_queue is: 100
❮ C++ - Priority Queue