Priority Queue in C++
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:
Note: The priority queue is the extended version of a normal queue except that the element with the highest priority will be removed first from the priority queue.
Syntax of Priority Queue
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.
Member Function of 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