priority_queue::top() method

A priority queue is a dynamically resizing container adopter 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. The priority_queue::top() is a method available in the STL which returns a constant reference to the top element (first element) in the priority queue.

Syntax:

priorityq_name.top();

Parameters: The priority_queue::top() does not accept any parameter.
Return value: A reference to the top element in the priority queue.

Example of priority_queue::top() method

#include <iostream>>
#include <queue>

using namespace std;


int main ()
{
    priority_queue<int> q1;

    q1.push(10);
    q1.push(20);
    q1.push(40);
    q1.push(30);
    q1.push(50);

    cout<<"Top element is: "<<q1.top();

    return 0;
}

Output:

Top element is: 50

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Full Stack Integrated Bootcamp Free Trial

  • Please enter a number from 7000000000 to 9999999999.