FastLED 3.9.15
Loading...
Searching...
No Matches
priority_queue.h
Go to the documentation of this file.
1#pragma once
2
3#include "fl/functional.h"
4#include "fl/vector.h"
5
6namespace fl {
7
8// Custom heap operations
9template <typename Iterator, typename Compare>
10void sift_down(Iterator first, Iterator last, Iterator start, Compare comp) {
11 auto root = start;
12 auto child = first + 2 * (root - first) + 1;
13
14 while (child < last) {
15 if (child + 1 < last && comp(*child, *(child + 1))) {
16 ++child;
17 }
18
19 if (comp(*root, *child)) {
20 auto tmp = *root;
21 *root = *child;
22 *child = tmp;
23
24 root = child;
25 child = first + 2 * (root - first) + 1;
26 } else {
27 break;
28 }
29 }
30}
31
32template <typename Iterator, typename Compare>
33void push_heap(Iterator first, Iterator last, Compare comp) {
34 auto pos = last - 1;
35 auto parent = first + ((pos - first) - 1) / 2;
36
37 while (pos > first && comp(*parent, *pos)) {
38 auto tmp = *parent;
39 *parent = *pos;
40 *pos = tmp;
41
42 pos = parent;
43 parent = first + ((pos - first) - 1) / 2;
44 }
45}
46
47template <typename Iterator> void push_heap(Iterator first, Iterator last) {
48 push_heap(first, last, [](const auto &a, const auto &b) { return a < b; });
49}
50
51template <typename Iterator, typename Compare>
52void pop_heap(Iterator first, Iterator last, Compare comp) {
53 --last;
54 auto tmp = *first;
55 *first = *last;
56 *last = tmp;
57
58 sift_down(first, last, first, comp);
59}
60
61template <typename Iterator> void pop_heap(Iterator first, Iterator last) {
62 pop_heap(first, last, [](const auto &a, const auto &b) { return a < b; });
63}
64
65template <typename T, typename Compare = fl::less<T>,
66 typename VectorT = fl::HeapVector<T>>
68 public:
69 using value_type = T;
70 using size_type = size_t;
71 using compare_type = Compare;
72
73 PriorityQueue() = default;
74 explicit PriorityQueue(const Compare &comp) : _comp(comp) {}
75
76 void push(const T &value) {
77 _data.push_back(value);
78 push_heap(_data.begin(), _data.end(), _comp);
79 }
80
81 void pop() {
82 pop_heap(_data.begin(), _data.end(), _comp);
83 _data.pop_back();
84 }
85
86 const T &top() const { return _data.front(); }
87
88 bool empty() const { return _data.size() == 0; }
89 size_type size() const { return _data.size(); }
90
91 const Compare &compare() const { return _comp; }
92
93 private:
94 VectorT _data;
95 Compare _comp;
96};
97
98} // namespace fl
uint8_t pos
Definition Blur.ino:11
PriorityQueue(const Compare &comp)
size_type size() const
PriorityQueue()=default
const T & top() const
const Compare & compare() const
void push(const T &value)
bool empty() const
void sift_down(Iterator first, Iterator last, Iterator start, Compare comp)
void pop_heap(Iterator first, Iterator last, Compare comp)
void push_heap(Iterator first, Iterator last, Compare comp)
Implements a simple red square effect for 2D LED grids.
Definition crgb.h:16