Implement the Main Function
The main
function is where all the action happens. We first declare an integer variable i
. Then we create a priority queue of integers names q
. We then add some integers to the priority queue using the push
function.
After that, we display the elements present in the priority queue using the show
function. We then use the size
function to display the number of elements present in the queue, and we use the top
function to display the element with the highest priority.
Next, we use the pop
function to remove the element with the highest priority and display the updated priority queue using the show
function.
int main()
{
priority_queue<int> q;
for (int i = 1; i < 6; i++)
{
q.push(i * 10);
}
cout << "The Priority Queue is: ";
show(q);
cout << "\n\nThe number of elements in the Priority Queue are: " << q.size();
cout << "\n\nThe element with the highest priority is: " << q.top();
q.pop();
cout << "\n\nAfter Deleting the top most element, Priority Queue becomes: ";
show(q);
return 0;
}
Final Code
You can use the following code to implement Priority Queue in C++:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void show(priority_queue<int> q)
{
priority_queue<int> pq = q;
while (!pq.empty())
{
cout << "\t" << pq.top();
pq.pop();
}
cout << endl;
}
int main()
{
priority_queue<int> q;
for (int i = 1; i < 6; i++)
{
q.push(i * 10);
}
cout << "The Priority Queue is: ";
show(q);
cout << "\n\nThe number of elements in the Priority Queue are: " << q.size();
cout << "\n\nThe element with the highest priority is: " << q.top();
q.pop();
cout << "\n\nAfter Deleting the top most element, Priority Queue becomes: ";
show(q);
return 0;
}
Save the above code in ~/project/main.cpp
. To compile and run this code, use the following commands:
g++ main.cpp -o main && ./main