The priority queue in C++ is a derived container in STL that considers only the highest priority element. The queue follows the FIFO policy while priority queue pops the elements based on the priority, i.e., the highest priority element is popped first.
It is similar to the ordinary queue in certain aspects but differs in the following ways:
Let's understand the priority queue through a simple example.
In the above illustration, we have inserted the elements by using a push() function, and the insert operation is identical to the normal queue. But when we delete the element from the queue by using a pop() function, then the element with the highest priority will be deleted first.
|push()||It inserts a new element in a priority queue.|
|pop()||It removes the top element from the queue, which has the highest priority.|
|top()||This function is used to address the topmost element of a priority queue.|
|size()||It determines the size of a priority queue.|
|empty()||It verifies whether the queue is empty or not. Based on the verification, it returns the status.|
|swap()||It swaps the elements of a priority queue with another queue having the same type and size.|
|emplace()||It inserts a new element at the top of the priority queue.|
Let's create a simple program of priority queue.
In the above code, we have created a priority queue in which we insert three elements, i.e., 10, 30, 20. After inserting the elements, we display all the elements of a priority queue by using a while loop.
Number of elements available in 'p' :3 30 20 10 zzzzz/
Let's see another example of a priority queue.
In the above code, we have declared two priority queues, i.e., p and q. We inserted four elements in 'p' priority queue and four in 'q' priority queue. After inserting the elements, we swap the elements of 'p' queue with 'q' queue by using a swap() function.
Elements of p are : 8 7 6 5 Elements of q are : 4 3 2 1