-
We start by including the necessary headers: iostream for input/output and vector for using a dynamic array.
-
Next, we define the PriorityQueue class as a template class. The heap member variable is a vector that will store the elements of the priority queue.
-
The heapifyUp function is used to maintain the heap property by moving an element up the heap until it is in the correct position. It takes an index as a parameter and compares the element at that index with its parent. If the element is smaller than its parent, they are swapped, and the process continues with the updated index until the element is in the correct position or reaches the root.
-
The heapifyDown function is used to maintain the heap property by moving an element down the heap until it is in the correct position. It takes an index as a parameter and compares the element at that index with its children. If the element is larger than either of its children, it is swapped with the smallest child, and the process continues with the updated index until the element is in the correct position or reaches a leaf node.
-
The empty function checks if the priority queue is empty by checking if the heap vector is empty.
-
The size function returns the size of the priority queue, which is the size of the heap vector.
-
The push function adds an element to the priority queue. It takes a value as a parameter, pushes it to the back of the heap vector, and then calls heapifyUp to maintain the heap property.
-
The pop function removes the top (smallest) element from the priority queue. It swaps the first element with the last element in the heap vector, pops the last element, and then calls heapifyDown to maintain the heap property.
-
The top function returns the top (smallest) element of the priority queue. It simply returns the first element of the heap vector.
-
In the main function, we create an instance of the PriorityQueue class (pq).
-
We push some integers into the priority queue using the push function.
-
We then enter a while loop that continues until the priority queue is empty. Inside the loop, we print the top element of the priority queue using the top function