Practical Examples
Real-World Priority Queue Applications
1. Task Scheduling System
#include <queue>
#include <string>
#include <iostream>
struct Task {
int priority;
std::string name;
// Custom comparison for priority queue
bool operator<(const Task& other) const {
return priority < other.priority;
}
};
class TaskScheduler {
private:
std::priority_queue<Task> taskQueue;
public:
void addTask(const std::string& name, int priority) {
taskQueue.push({priority, name});
}
void executeTasks() {
while (!taskQueue.empty()) {
Task currentTask = taskQueue.top();
taskQueue.pop();
std::cout << "Executing task: "
<< currentTask.name
<< " (Priority: "
<< currentTask.priority
<< ")\n";
}
}
};
Task Scheduling Flow
graph TD
A[Add Tasks] --> B{Priority Queue}
B --> C[Highest Priority Task]
C --> D[Execute Task]
D --> E{More Tasks?}
E -->|Yes| C
E -->|No| F[Scheduling Complete]
2. Dijkstra's Shortest Path Algorithm
#include <queue>
#include <vector>
#include <utility>
class Graph {
private:
std::vector<std::vector<std::pair<int, int>>> adjacencyList;
void dijkstraShortestPath(int start) {
std::priority_queue<
std::pair<int, int>,
std::vector<std::pair<int, int>>,
std::greater<std::pair<int, int>>
> pq;
std::vector<int> distances(adjacencyList.size(), INT_MAX);
pq.push({0, start});
distances[start] = 0;
while (!pq.empty()) {
int currentVertex = pq.top().second;
int currentDistance = pq.top().first;
pq.pop();
// Process adjacent vertices
for (auto& neighbor : adjacencyList[currentVertex]) {
int nextVertex = neighbor.first;
int edgeWeight = neighbor.second;
if (currentDistance + edgeWeight < distances[nextVertex]) {
distances[nextVertex] = currentDistance + edgeWeight;
pq.push({distances[nextVertex], nextVertex});
}
}
}
}
};
Comparison of Priority Queue Use Cases
Use Case |
Primary Benefit |
Time Complexity |
Task Scheduling |
Execute highest priority tasks first |
O(log n) |
Shortest Path |
Efficiently find minimal path |
O((V+E)log V) |
Event Simulation |
Process events by priority |
O(log n) |
3. Event-Driven Simulation
#include <queue>
#include <functional>
class EventSimulator {
private:
std::priority_queue<
std::pair<double, std::function<void()>>,
std::vector<std::pair<double, std::function<void()>>>,
std::greater<std::pair<double, std::function<void()>>>
> eventQueue;
public:
void scheduleEvent(double time, std::function<void()> event) {
eventQueue.push({time, event});
}
void runSimulation() {
while (!eventQueue.empty()) {
auto currentEvent = eventQueue.top();
eventQueue.pop();
// Execute event at specified time
currentEvent.second();
}
}
};
Key Takeaways for LabEx Learners
- Priority queues solve complex ordering problems
- Flexible implementation across various domains
- Understand trade-offs in different use cases
At LabEx, we emphasize practical application of data structures to solve real-world challenges.