How is the priority_queue used in C++?
In C++, a priority_queue is a container adaptor that implements a priority queue. A priority queue is a special type of container where each element has a priority. Unlike a regular queue, the elements in a priority queue are sorted by priority rather than by the order of insertion.
You can include the priority_queue template class in your code using the following code in the header file.
#include <queue>
Common methods and operations of a priority queue include:
- Insert the element into the priority queue using push(element).
- pop(): Removes the top element from the priority queue.
- top(): Access the top element in the priority queue.
- size(): returns the number of elements in the priority queue.
- empty(): Check if the priority queue is empty.
Elements in a priority queue are sorted by default based on the “<" operator of the element type, so the element type must support comparison using the "<" operator. Alternatively, you can change the sorting rule of elements by passing a custom comparison function.
Here is a simple example using a priority_queue:
#include <iostream>
#include <queue>
int main() {
std::priority_queue<int> pq;
pq.push(10);
pq.push(5);
pq.push(15);
std::cout << "Size of priority queue: " << pq.size() << std::endl;
std::cout << "Top element: " << pq.top() << std::endl;
pq.pop();
std::cout << "Size of priority queue after pop: " << pq.size() << std::endl;
std::cout << "New top element: " << pq.top() << std::endl;
return 0;
}
This example creates a priority_queue that stores integers. It then inserts three integers and prints the size of the queue and the top element. Next, it pops an element from the queue and prints the size of the queue again along with the new top element.
The output is:
Size of priority queue: 3
Top element: 15
Size of priority queue after pop: 2
New top element: 10