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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?