STL (Standard Template Library) priority queue in C++. The priority queue is an ordered container adapter provided by the C++ STL that allows efficient retrieval of the highest-priority element.
#include<queue>
std::priority_queue<DataType> myPriorityQueue;
Replace DataType with the actual data type you want to store in the priority queue.
You can use the push member function to insert elements into the priority queue. The elements will be automatically sorted based on their priority.
myPriorityQueue.push(element);
To access the highest-priority element in the priority queue, you can use the top member function.
DataType highestPriorityElement = myPriorityQueue.top();
To remove the highest-priority element from the priority queue, you can use the pop member function. This will remove the element with the highest priority, and the next highest-priority element will become the new top.
myPriorityQueue.pop();
By default, the priority queue orders elements in descending order (largest element at the top). However, you can customize the priority order by defining a comparison function or using a lambda function.
If you want the smallest element to have the highest priority, you can use the following syntax:
std::priority_queue<DataType, std::vector<DataType>, std::greater<DataType>> myPriorityQueue;
This member function returns the number of elements in the priority queue. It provides the current size of the priority queue by counting the number of elements present.
std::priority_queuemyPriorityQueue; myPriorityQueue.push(5); myPriorityQueue.push(10); int size = myPriorityQueue.size(); // size is 2
This member function checks whether the priority queue is empty or not. It returns true if the priority queue is empty (contains no elements), and false otherwise.
std::priority_queuemyPriorityQueue; bool isEmpty = myPriorityQueue.empty(); // isEmpty is true myPriorityQueue.push(5); isEmpty = myPriorityQueue.empty(); // isEmpty is false
This member function removes all elements from the priority queue, leaving it empty. It effectively clears the priority queue by removing all elements. After calling clear(), the priority queue will have a size of 0.
std::priority_queuemyPriorityQueue; myPriorityQueue.push(5); myPriorityQueue.push(10); myPriorityQueue.clear(); // The priority queue is now empty