C++ Standard Library C++ STL Library

C++ priority_queue - top() Function



The C++ priority_queue::top function returns 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 example below, the priority_queue::top function is used to access the top element of the priority_queue called pqueue.

#include <iostream>
#include <queue>
using namespace std;
 
int main (){
  priority_queue<int> pqueue;

  //add new elements in the priority_queue
  pqueue.push(100);
  pqueue.push(80);
  pqueue.push(990);
  pqueue.push(85);
  pqueue.push(10);

  cout<<"The top element of pqueue is: ";
  cout<<pqueue.top();

  cout<<"\n\nDelete the top element of the pqueue.\n";
  pqueue.pop();

  cout<<"Now, The top element of pqueue is: ";
  cout<<pqueue.top();  
  return 0;
}

The output of the above code will be:

The top element of pqueue is: 990

Delete the top element of the pqueue.
Now, The top element of pqueue is: 100

❮ C++ <queue> Library