C++ Access Element from the Priority Queue

www.‮figi‬tidea.com

To access the element at the top of a priority queue in C++, you can use the top() method. This method returns a reference to the top element, which is the element with the highest priority in the priority queue.

Here's an example:

#include <iostream>
#include <queue>

int main() {
    std::priority_queue<int> pq;
    pq.push(3);
    pq.push(1);
    pq.push(4);

    std::cout << "Top element: " << pq.top() << std::endl;

    return 0;
}

Output:

Top element: 4

In this example, we create a priority queue of integers and insert three elements: 3, 1, and 4. The top() method returns a reference to the element with the highest priority, which in this case is 4. We then print the value of the top element to the console.