Working with priority_queue in C++
Understanding priority\_queue in C++
The priority\_queue is a crucial container within the C++ Standard Template Library (STL). While it shares some similarities with a standard queue, it differs significantly in behavior:
- Top-priority element is always at front: The queue organizes its elements based on a priority scheme. The highest (or lowest) priority element remains at the front and is removed first during a dequeue operation.
- Internally implemented using a heap: By default,
priority\_queueuses avectoras its underlying storage. It transforms this vector into a heap structure using standard heap adjustment algorithms.
Template Definition of priority\_queue
Here is how the priority\_queue class template is defined in C++:
template<
class T,
class Container = vector<T>,
class Compare = less<typename Container::value_type>
> class priority_queue;
Trepresenst the data type of elements stored in the queue.Containeris the underlying storage type, defaulting tovector.Compareis an optional comparator used to determine ordering. By default, it usesstd::less, which results in a max-heap. Alternatively,std::greatercan be used to create a min-heap.
Basic Usage Examples
-
Declaring a
priority\_queue: To use a priority queue, include the appropriate header:#include <queue>. You may also useusing namespace std;to simplify syntax. The declaration follows the standard STL container pattern:priority_queue<typename> name; -
Accessing the highest-priority element: Unlike a standard queue,
priority\_queuedoes not supportfront()orback(). Instead, the top element is accessed via thetop()method. Here's a basic example:#include <queue> using namespace std; int main() { priority_queue<int> pq; pq.push(3); pq.push(4); pq.push(1); printf("%d\n", pq.top()); // Outputs 4 return 0; } -
Key operations and time complexity:
push(x): Adds an element to the queue. Time cmoplexity: O(log N).top(): Retrieves the top element. Time complexity: O(1).pop(): Removes the top element. Time complexity: O(log N).empty(): Checks if the queue is empty. Time complexity: O(1).size(): Returns the number of elements. Time complexity: O(1).
-
Customizing priority rules: For basic data types, higher numeric values mean higher priority by default. However, for user-defined types like structs, you can define custom ordering by overloading the less-than operator (
<).