/
PriorityQueue.hpp
130 lines (89 loc) · 2.76 KB
/
PriorityQueue.hpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* Copyright 2017 Kjetil S. Matheussen
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
namespace radium {
template <typename Event> struct PriorityQueue {
private:
int _queue_size = 0;
int _max_queue_size;
Event _event0 = {};
Event **_queue;
public:
PriorityQueue(int max_queue_size, double a_lower_priority_than_we_will_ever_add = -10000)
: _max_queue_size(max_queue_size + 2)
{
_queue = (Event**)V_calloc(sizeof(Event*), _max_queue_size);
_event0.priority = a_lower_priority_than_we_will_ever_add;
_queue[0] = &_event0;
}
~PriorityQueue(){
V_free(_queue);
}
bool add(Event *event){
if(_queue_size > _max_queue_size-2)
return false;
_queue_size++;
Event **queue = _queue;
int i = _queue_size;
int new_i = i >> 1;
auto priority = event->priority;
while(priority < queue[new_i]->priority){
queue[i] = queue[new_i];
i = new_i;
new_i = new_i >> 1;
}
queue[i] = event;
return true;
}
void remove_first_event(void){
R_ASSERT_RETURN_IF_FALSE(_queue_size > 0);
Event **queue = _queue;
Event *last = queue[_queue_size];
auto last_priority = last->priority;
int i = 1;
int child = 2;
_queue_size--;
int queue_size = _queue_size;
while(child <= queue_size){
if(child != queue_size
&& queue[child+1]->priority < queue[child]->priority)
child++;
if(last_priority <= queue[child]->priority)
break;
queue[i] = queue[child];
i = child;
child = child * 2;
}
queue[i] = last;
queue[queue_size+1] = NULL;
}
Event *get_first_event(void){
if (_queue_size==0)
return NULL;
return _queue[1];
}
Event *get_event_n(int n){
R_ASSERT_RETURN_IF_FALSE2(n<_queue_size,NULL);
return _queue[1+n];
}
// Note: Iteration is not in priority order, just the order it is stored internally.
Event* const *begin() const {
return &_queue[1];
}
Event* const *end() const {
return &_queue[_queue_size+1];
}
int size(void) const {
return _queue_size;
}
};
}