C++ Priority Queue Top - C++ Programming Tutorial
C++ Course / Data Structures / C++ Priority Queue Top

C++ Priority Queue Top

BLUF: Mastering C++ Priority Queue Top is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Priority Queue Top

C++ is renowned for its efficiency. Learn how C++ Priority Queue Top enables low-level control and high-performance computing in the tutorial below.

In C++, the priority_queue::top method stands out as a commonly used container adapter within the Standard Template Library (STL). This function grants access to the element with the highest priority within the priority queue, contrary to the conventional First-In-First-Out (FIFO) principle. Consequently, the top element in the container always reflects the highest priority element.

In C++, the top method plays a significant role in priority queues as it is frequently employed to retrieve the element with the highest priority in the queue without deleting it from the data structure. In the context of a max heap, this would correspond to the maximum element, whereas in a min heap (utilizing a comparator such as greater<T>), it would represent the minimum element.

Syntax:

It has the following syntax:

Example

priority_queue<data_type> pq;

pq.top();

Parameter: It does not take any parameters.

Return value: It returns a reference to the top element of the priority queue.

  • In a max-heap priority queue (default), top returns the maximum element.
  • In a min-heap priority queue (custom comparator using std::greater<T>), top returns the minimum element.

By utilizing the top function, we are not eliminating the element with the highest priority from the collection. Instead, we are simply retrieving a reference to the element with the highest priority within the collection.

C++ Simple Example using priority_queue::top Function

Let's consider an instance to demonstrate the functionality of the priority_queue::top method in C++.

Example

Example

#include <iostream>  

#include <queue>  

using namespace std;    //using standard namespace

int main()    //main function

{  

int sum = 0;  

priority_queue<int> pqueue;  

 //pushing value in pqueue.  

pqueue.push(8);  

pqueue.push(6);  

pqueue.push(3);  

pqueue.push(2);  

pqueue.push(1);  

cout<<pqueue.top();  

return 0;  

}

Output:

Explanation:

In this instance, we are working with a priority_queue that holds integers along with multiple values. As the priority queue functions as a max-heap, we utilize the top method to retrieve the highest element present in the queue.

C++ priority_queue::top Example Using Min-Heap

Let's consider a scenario to demonstrate the priority_queue::top method with a Min-Heap in C++.

Example

Example

#include <iostream>

#include <queue>

using namespace std;

int main() {

    priority_queue<int, vector<int>, greater<int>> minHeap;

    minHeap.push(10);

    minHeap.push(30);

    minHeap.push(20);

    minHeap.push(5);

    cout << "The top element (minimum) is: " << minHeap.top() << endl;

    return 0;

}

Output:

Output

The top element (minimum) is: 5

Explanation:

In this instance, a custom comparator named greater<int> is implemented to offer a priority queue with the characteristics of a min-heap. Subsequently, items are added to the heap, and calling top will retrieve the smallest element, in this case 5, without dequeuing it.

C++ Example to modify the Top Element of a Priority Queue

Let's consider an instance where we need to alter the highest-priority items in a priority queue using C++.

Example

Example

#include <iostream>

#include <queue>

using namespace std;

int main() {

    priority_queue<int> pq;

    pq.push(50);

    pq.push(40);

    pq.push(60);

    cout << "Original top: " << pq.top() << endl;

    // Modify top element

    int &topElement = const_cast<int&>(pq.top());

    topElement = 100;

    cout << "Modified top: " << pq.top() << endl;

    return 0;

}

Output:

Output

Original top: 60

Modified top: 100

Explanation:

In this instance, we are constructing a priorityqueue with a max-heap configuration, where the top method is frequently employed to retrieve the highest value. Subsequently, the constcast feature is employed to enable direct alteration of the foremost element.

C++ priority_queue example with Pairs for Minimum Distance Selection

Priority queues are commonly used in graph algorithms. For instance, in Dijkstra's algorithm, we depend on the top function to fetch the node with the smallest distance. To demonstrate this, let's consider an example showcasing the propriety_queue::top method for selecting the pair with the minimum distance in C++.

Example

Example

#include <iostream>

#include <queue>

#include <vector>

using namespace std;    //using standard namespace

int main() {   //main function

    // Min-heap for Dijkstra (distance, node)

    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;

    pq.push({0, 1});  // distance = 0, node = 1

    pq.push({2, 2});

    pq.push({1, 3});

    cout << "Node with smallest distance: " << pq.top().second << endl;

    return 0;

}

Output:

Output

Node with smallest distance: 1

Explanation:

In this instance, the min-heap guarantees that the pair containing the smallest distance (0, node 1) will consistently remain at the top position.

Features of priority_queue::top function in C++

There are several key features of the priority_queue::top function in C++. Some of them are as follows:

  • In C++, the priority_queue::top function provide the constant-time (O(1)) access.
  • It can perform operations differently for a max-heap and a min-heap.
  • It doesn't allow us to remove the element from the queue.
  • It returns the element with the highest priority in C++.
  • Conclusion

To sum up, the priority_queue::top method in C++ proves to be an invaluable tool by swiftly retrieving the element with the highest priority. Essentially, this function provides the largest value in a max-heap structure, although with the ability to customize comparators, it can also deliver the smallest value. This function is straightforward to apply and highly effective in scenarios like scheduling systems, graph algorithms, event-driven simulations, and various other software implementations.

C++ Priority_queue::top Function FAQs

1) What does priority_queue::top return in C++?

In C++, the top function within a priority queue provides a reference to an element, specifically the one with the highest priority. When the priority queue functions as a max-heap, it will retrieve the largest value. Conversely, if a custom comparator like greater is implemented, it will fetch the smallest value instead.

No, the top function in C++ does not remove the element from the priority queue. It only returns the element with the highest priority without modifying the queue itself.

The top method exclusively provides access to the element with the highest priority without altering or deleting it. To eliminate this element, the pop method should be invoked. Nevertheless, top primarily serves the purpose of retrieving the value, and pop is usually executed immediately after to eliminate it.

When calling top on an empty priority queue, it will result in an error or exception being thrown, depending on the programming language or library being used. This is because the top function is intended to retrieve the element with the highest priority in the priority queue, and if the priority queue is empty, there is no element to return as the highest priority. Therefore, attempting to call top on an empty priority queue violates the expected behavior and may lead to a runtime error.

When invoking the top function on an empty priority queue, it can lead to undefined behavior that might result in program crashes. To prevent this, it is crucial to verify the queue's emptiness using the empty function prior to accessing the top element.

4) Is it possible to alter the value that is returned by the top function?

Yes, it is possible as top provides a reference enabling direct value modification. This action alters the value derived from top, potentially disrupting the heap structure of the priority queue and leading to unexpected outcomes. To avoid this, it is recommended to use pop to remove the element and then push the modified value back into the queue.

5) When is the top function useful?

In C++, the top function is extremely beneficial as it provides a convenient method to access the element with the highest priority. This functionality proves to be invaluable in various algorithms such as Dijkstra's shortest path, job scheduling, and event-driven systems.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience