C++ Queue Library - top() Function



Description

The C++ function std::priority_queue::top() returns a reference to the first element of the priority_queue. This element will be removed after performing pop operation on priority_queue.

Declaration

Following is the declaration for std::priority_queue::top() function form std::queue header.

C++98

const value_type& top() const;

C++11

const_reference top() const;

Parameters

None

Return value

Returns reference to the top element of the priority_queue.

Exceptions

This member function never throws exception.

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::priority_queue::top() function.

#include <iostream>
#include <queue>

using namespace std;

int main(void) {
   auto it = {3, 1, 5, 2, 4};
   priority_queue<int> q(less<int>(), it);

   cout << "Queue contents are" << endl;
   while (!q.empty()) {
      cout << q.top() << endl;
      q.pop();
   }

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Queue contents are
5
4
3
2
1
queue.htm
Advertisements