C++ STL Priority Queue – std::priority_queue

In this tutorial you will learn about STL priority queue in C++ i.e std::priority_queue and all functions applicable on it.

std:: priority_queue is a container adaptor. This is almost same as queue container adaptor. i.e this also works as first in first out (FIFO). Elements always inserted at front position and deletion also done from front position. But only difference is elements in the priority queue has some priority. In this priority queue the element which is at top position has highest priority.

To use priority queue we simply include queue header file. There is no special priority queue header file. We include queue header file but to gain property of priority to the elements we declare as priority_queue. See below for more understanding.

C++ STL Priority Queue – std::priority_queue

#include <queue> // this is enough to work with priority queue. But while declaring do

priority_queue <data type> priority queue name;

The functions associated with priority queue are:

push (element): To insert element into priority queue we use push operation.

pop(): To remove element from priority queue we use pop operation.

size(): To know the size of the priority queue we use size function. It returns number of elements that are present in priority queue.

top(): To get the first top element we use top function. It returns the most priority element in priority queue.

empty(): empty is a Boolean function which returns true if the priority queue is empty, otherwise returns false if priority queue is not empty.

swap():  If there are two priority queues with swap operation we can exchange all elements from priority queue1 to priority queue2 and vice versa. Here constraints are both must contain same data type of elements. But both sizes need not be equal.

Example program to show all above functions:

Output

the elements in priority queue are
5 4 3 2 1
size of the priority queue is 5
top element in priority queue is 5
performing one pop operation…
result after pop operation 4 3 2 1
priority queue is not empty

Priority queue 1 elements before swapping are
4 3 2 1

Priority queue 2 elements before swapping are
40 30 20 10 0

Priority queue 1 elements after swapping are
40 30 20 10 0

Priority queue 2 elements after swapping are
4 3 2 1

Leave a Reply

Your email address will not be published. Required fields are marked *