How do I insert and erase elements efficiently with std::priority_queue?

In C++, the std::priority_queue is a container adaptor that provides constant time lookup of the greatest element and logarithmic time complexity for insertion and removal of elements. However, it does not support direct insertion or deletion of arbitrary elements efficiently. To insert or erase elements efficiently, you might consider using alternative data structures in combination with priority queues or extend the functionality yourself.

Here is an example demonstrating how to use std::priority_queue:

#include #include #include int main() { // Create a max-heap priority queue std::priority_queue pq; // Inserting elements pq.push(10); pq.push(5); pq.push(20); pq.push(15); std::cout << "Top element: " << pq.top() << std::endl; // Outputs the largest element // Removing elements pq.pop(); // Removes the max element (20) std::cout << "New top element after pop: " << pq.top() << std::endl; // Outputs the next largest element return 0; }

C++ std::priority_queue insertion deletion max-heap container adaptor data structure