Skip to content
Related Articles

Related Articles

Improve Article
priority_queue::top() in C++ STL
  • Difficulty Level : Medium
  • Last Updated : 13 Jan, 2018


Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is the greatest of all elements in the queue.

priority_queue::top()

top() function is used to reference the top(or the largest) element of the priority queue.
Syntax :

pqueuename.top()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the top(or the largest)
element of the priority queue container.

Examples:

Input  : pqueue.push(5);
         pqueue.push(1);
         pqueue.top();
Output : 5

Input  : pqueue.push(5);
         pqueue.push(1);
         pqueue.push(7);
         pqueue.top();
Output : 7

Errors and Exceptions

1. If the priority queue container is empty, it causes undefined behaviour
2. It has a no exception throw guarantee if the priority queue is not empty






// CPP program to illustrate
// Implementation of top() function
#include <iostream>
#include <queue>
using namespace std;
  
int main()
{
    priority_queue<int> pqueue;
    pqueue.push(5);
    pqueue.push(1);
    pqueue.push(7);
  
    // Priority queue top
    cout << pqueue.top();
    return 0;
}

Output:

7

Application :
Given a priority queue of integers, find the number of prime and non prime numbers.

Input : 8, 6, 3, 2, 1
Output: Prime - 2
        Non Prime - 3

Algorithm
1. Enter the size of the priority queue into a variable.
2. Check if the priority queue is empty, check if the top element is prime, if prime increments the prime counter, and pop the top element.
3. Repeat this step until the priority queue is empty.
4. Print the final value of the variable prime and nonprime(size – prime).




// CPP program to illustrate
// Application of top() function
#include <iostream>
#include <queue>
using namespace std;
  
int main()
{
    int prime = 0, nonprime = 0, size;
    priority_queue<int> pqueue;
    pqueue.push(1);
    pqueue.push(8);
    pqueue.push(3);
    pqueue.push(6);
    pqueue.push(2);
    size = pqueue.size();
  
    // Priority queue becomes 1, 8, 3, 6, 2
  
    while (!pqueue.empty()) {
        for (int i = 2; i <= pqueue.top() / 2; ++i) {
            if (pqueue.top() % i == 0) {
                prime++;
                break;
            }
        }
        pqueue.pop();
    }
    cout << "Prime - " << prime << endl;
    cout << "Non Prime - " << size - prime;
    return 0;
}

Output:

Prime - 2
Non Prime - 3
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :