Priority queue in C++
In this post, you will learn how to implement a Priority Queue in C++ programming language.
The priority of the element is used to determine the order in which the elements will be processed. The elements in the priority queue have some priority. In this element, it is inserted and deleted based on its priority.
The basic examples of Priority Queue-
- Routing
- Operating System Scheduler
- Dijkstra's Shortest Path Algorithm
- Huffman Coding
These are the rules for processing elements in a priority queue.
- The element with the highest priority is processed first.
- The two elements with equal priority are processed based on a First Come First Serve(FCFS) basis.
The priority of the elements is set based on several factors. This is basically used in the operating system to execute the most priority process first. If this is set on the CPU time, then the element with the lowest execution time is executed first. Suppose there are two processes in a queue, one has 5ns execution time and the other has 10ns execution time, then the process having 5ns executes first.
C++ program to insert a given element into a priority queue
#include <iostream>
#include <queue>
using namespace std;
void displaypq(priority_queue<int> pq)
{
priority_queue<int> g = pq;
while (!g.empty()) {
cout << '\t' << g.top();
g.pop();
}
cout << '\n';
}
// Driver Code
int main()
{
priority_queue<int> my_queue;
my_queue.push(15);
my_queue.push(33);
my_queue.push(25);
my_queue.push(11);
my_queue.push(42);
cout << "The priority queue is: ";
displaypq(my_queue);
cout << "\nNumber of elements available: " << my_queue.size();
cout << "\nTop Element: " << my_queue.top();
cout << "\nPop the element: ";
my_queue.pop();
displaypq(my_queue);
return 0;
}
Output of the above code:
The priority queue is: 42 33 25 15 11
Number of elements available: 5
Top Element: 42
Pop the element: 33 25 15 11
Related Articles
Queue implementation in c++Queue using linked list c++
Swapping of two numbers in C++
Generate random numbers in C++
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative