STL Priority Queue in C++

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.

Header file
#include<queue>
Declare a priority queue
std::priority_queue<DataType> myPriorityQueue;

Replace DataType with the actual data type you want to store in the priority queue.

Insert elements into 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);
Accessing highest-priority element

To access the highest-priority element in the priority queue, you can use the top member function.

DataType highestPriorityElement = myPriorityQueue.top();
Removing highest-priority element

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();
Customizing priority order

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.

Example

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;
Other member functions and operations
size()

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.

Example
std::priority_queue myPriorityQueue;
myPriorityQueue.push(5);
myPriorityQueue.push(10);
int size = myPriorityQueue.size(); // size is 2
empty()

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.

Example
std::priority_queue myPriorityQueue;
bool isEmpty = myPriorityQueue.empty(); // isEmpty is true
myPriorityQueue.push(5);
isEmpty = myPriorityQueue.empty(); // isEmpty is false
clear()

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.

Example
std::priority_queue myPriorityQueue;
myPriorityQueue.push(5);
myPriorityQueue.push(10);
myPriorityQueue.clear(); // The priority queue is now empty