-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyPriorityQueue.h
65 lines (57 loc) · 1.19 KB
/
MyPriorityQueue.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#ifndef MY_PRIORITY_QUEUE
#define MY_PRIORITY_QUEUE
#include <map>
#include <cmath>
template<class T>
class MyPriorityQueue {
std::map<T, double> _queue;
T _minimumObject;
double _minimumValue;
public:
MyPriorityQueue(): _minimumObject(nullptr), _minimumValue(NAN) {}
void push(T& obj, const double value) {
_queue[obj] = value;
if (value < _minimumValue) {
_minimumObject = obj;
_minimumValue = value;
}
else if (std::isnan(_minimumValue)) {
_minimumObject = obj;
_minimumValue = value;
}
}
const T pop() {
if (_queue.empty())
throw "The priority queue is empty";
T prevMinimum = _minimumObject;
_queue.erase(_minimumObject);
_minimumObject = _queue.begin()->first;
_minimumValue = _queue.begin()->second;
for (auto pair : _queue) {
if (pair.second < _minimumValue) {
_minimumObject = pair.first;
_minimumValue = pair.second;
}
}
if (_queue.empty()) {
_minimumObject = nullptr;
_minimumValue = NAN;
}
return prevMinimum;
}
bool exists(T& obj) const {
try {
_queue.at(obj);
return 1;
} catch (...) {
return 0;
}
}
bool empty() const {
return _queue.empty();
}
int size() const {
return _queue.size();
}
};
#endif