How do I sort and stable_sort elements with std::priority_queue?

In C++, the `std::priority_queue` is a container adapter that provides constant time lookup of the largest (or smallest) element. However, it does not support sorting or stable sorting directly. To sort elements using a priority queue, you can pop elements from the queue and push them into a sorted container like a vector or a list. Below is an example demonstrating how to use `std::priority_queue` to sort elements.

#include <iostream> #include <vector> #include <queue> #include <algorithm> int main() { std::priority_queue pq; // Inserting elements into the priority queue pq.push(5); pq.push(1); pq.push(3); pq.push(4); pq.push(2); // Vector to hold sorted elements std::vector sortedElements; // Pop all elements from the priority queue while (!pq.empty()) { sortedElements.push_back(pq.top()); pq.pop(); } // Reverse the sortedElements to have them in ascending order std::reverse(sortedElements.begin(), sortedElements.end()); // Display sorted elements for (int element : sortedElements) { std::cout << element << " "; } std::cout << std::endl; return 0; }

C++ std::priority_queue sort stable_sort container adapter