How to Implement Priority Queue Using Multimap in C++?
Last Updated :
16 Feb, 2024
A priority queue is a type of queue where elements are removed from the queue based on some priority. The element with the highest (or lowest priority depending on the type) will be removed first. Priority queues are fundamental data structures and are used in many applications like CPU scheduling, graph algorithms, and many others.
In this article, we will learn how to implement a priority queue using multimap in C++.
Priority Queue using Multimap in C++
Multimaps are the containers that store the sorted data in the form of key-value pairs. We can create a priority queue using multimaps because they both use binary tree data structures in their implementation. We will have to perform the following basic operations in the given time complexity:
- Push: O(log n)
- Pop: O(log n)
- Peek: O(1)
- empty: O(1)
For that, we will be using the keys as the priority and the data item as the values. The following program implements the min heap priority queue where the smallest key will be given the most priority and so on.
C++ Program to Implement Priority Queue using Multimap
C++
#include <iostream>
#include <map>
using namespace std;
template < typename T, typename Priority>
class PriorityQueue {
private :
multimap<Priority, T> elements;
public :
void push( const T& element, const Priority& priority)
{
elements.emplace(priority, element);
}
T pop()
{
if (elements.empty()) {
throw out_of_range( "Priority queue is empty" );
}
auto highestPriority = elements.begin();
T element = highestPriority->second;
elements.erase(highestPriority);
return element;
}
T peek() const
{
if (elements.empty()) {
throw out_of_range( "Priority queue is empty" );
}
return elements.begin()->second;
}
bool empty() const { return elements.empty(); }
};
int main()
{
PriorityQueue<string, int > pq;
pq.push( "Task 1" , 3);
pq.push( "Task 2" , 1);
pq.push( "Task 3" , 2);
pq.push( "Task 4" , 4);
cout << "Peeked task: " << pq.peek() << endl;
while (!pq.empty()) {
cout << pq.pop() << endl;
}
return 0;
}
|
Output
Peeked task: Task 2
Task 2
Task 3
Task 1
Task 4
Share your thoughts in the comments
Please Login to comment...