37 lines
904 B
C
37 lines
904 B
C
|
|
#pragma once
|
||
|
|
#include <queue>
|
||
|
|
#include <stdexcept>
|
||
|
|
#include <vector>
|
||
|
|
#include "WorkItem.h"
|
||
|
|
|
||
|
|
struct WorkItemComparator {
|
||
|
|
bool operator()(const WorkItem& a, const WorkItem& b) const {
|
||
|
|
return a.priority < b.priority; // max-heap: higher priority first
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
class PriorityQueue {
|
||
|
|
public:
|
||
|
|
void enqueue(WorkItem item) {
|
||
|
|
heap_.push(std::move(item));
|
||
|
|
}
|
||
|
|
|
||
|
|
WorkItem dequeue() {
|
||
|
|
if (heap_.empty()) throw std::underflow_error("queue is empty");
|
||
|
|
WorkItem top = heap_.top();
|
||
|
|
heap_.pop();
|
||
|
|
return top;
|
||
|
|
}
|
||
|
|
|
||
|
|
const WorkItem& peek() const {
|
||
|
|
if (heap_.empty()) throw std::underflow_error("queue is empty");
|
||
|
|
return heap_.top();
|
||
|
|
}
|
||
|
|
|
||
|
|
std::size_t size() const { return heap_.size(); }
|
||
|
|
bool empty() const { return heap_.empty(); }
|
||
|
|
|
||
|
|
private:
|
||
|
|
std::priority_queue<WorkItem, std::vector<WorkItem>, WorkItemComparator> heap_;
|
||
|
|
};
|