priority_queue::top() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is wither the greatest or the smallest of all elements in the queue. In general, elements are arranged according to some priority. However in C++ STL, the top element is the greatest element by default. We can also make a priority queue with a minimum element at the top by passing a additional parameter while creating the priority queue. It is similar to min/max heap.
top() function is used to reference the top element of the priority queue. The top (by default) element is the largest element in C++ STL.
However in other programming languages like java, by default a min heap is created and the top() gives the minimum element.
pqueuename.top() Parameters : No value is needed to pass as the parameter. Returns : Direct reference to the top(by default it is the largest element) element of the priority queue container.
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
Time Complexity: O(1)
Auxiliary Space: O(n)
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).
Prime - 2 Non Prime - 3
Time Complexity: O(nlogn)
Auxiliary Space: O(1)