Sobes.tech
Junior — Middle

Can you explain what a priority_queue data structure is and how it works?

sobes.tech AI

Answer from AI

The data structure priority_queue is a container that allows storing elements with priorities and quickly retrieving the element with the highest priority.

How it works:

  • Elements are inserted into the queue with a certain priority.
  • When extracting, the element with the maximum (or minimum, depending on the setting) priority is always returned.

In C++, priority_queue is implemented based on a heap, which provides insertion and extraction operations in O(log n).

Example of usage in C++:

#include <iostream>
#include <queue>

int main() {
    std::priority_queue<int> pq;
    pq.push(10);
    pq.push(5);
    pq.push(20);

    while (!pq.empty()) {
        std::cout << pq.top() << " "; // Will output: 20 10 5
        pq.pop();
    }
    return 0;
}

Here, pq.top() always returns the element with the highest value.