A glance at Priority Queue
Place for biased and undemocratic ones
Need of Priority Queue
Imagine you were implementing a queuing system for a hospital for its Accident and Emergency ward. If you were to use a traditional queue for people coming into the ward then you would see people with gunshot wounds or serious issues having to wait behind people who may require nothing more than an X-ray and possibly a cast over a minor break.
This queueing system would mean that people who had serious issues may end up not getting the treatment they need in appropriate time. This is where prioritization comes into play. When someone comes into the ward, the nurses prioritize those who have serious issues to the top of the queue so that they are seen first, they then prioritize those with relatively minor ailments to the back of the queue as they can afford to wait longer for treatment.
This is used in data structures and here priority queues shine .
Implementation of Priority Queue
The priority queue can be implemented in four ways that include :
- arrays
- linked lists
- heaps
- binary search trees
The heap data structure is the most efficient way of implementing the priority queue.
Priority Queue implementation using C++ STL
#include <iostream>
#include<queue>
using namespace std;
int main()
{
priority_queue<int> p; // variable declaration.
p.push(10); // inserting 10 in a queue, top=10
p.push(30); // inserting 30 in a queue, top=30
p.push(20); // inserting 20 in a queue, top=20
cout<<”Your Priority Queue :”<<p.size()<<endl;
while(!p.empty())
{
std::cout << p.top() << std::endl;
p.pop();
}
return 0;
}
The functions supported by queue are :-
push()
It inserts a new element in a priority queue.
pop()
It removes the top element from the queue, which has the highest priority.
top()
This function is used to address the topmost element of a priority queue.
size()
It determines the size of a priority queue.
empty()
It verifies whether the queue is empty or not. Based on the verification, it returns the status.
swap()
It swaps the elements of a priority queue with another queue having the same type and size.
emplace()
It inserts a new element at the top of the priority queue.
I hope you enjoyed this basic concept of “Priority Queue”.
Feel free to comment and like this article so that others can find it easily on Medium!
And thank you for reading this article if you like it then share it, with your friends and enemies .And endorse me so, that I will be writing more stay connected with me :)