Sequoia
Loading...
Searching...
No Matches
StaticPriorityQueue.hpp
Go to the documentation of this file.
1
2// Copyright Oliver J. Rosten 2018. //
3// Distributed under the GNU GENERAL PUBLIC LICENSE, Version 3.0. //
4// (See accompanying file LICENSE.md or copy at //
5// https://www.gnu.org/licenses/gpl-3.0.en.html) //
7
8#pragma once
9
17
18#include <functional>
19
20namespace sequoia::data_structures
21{
27 template<class T, std::size_t MaxDepth, class Compare=std::ranges::less>
29 {
30 public:
31 constexpr static_priority_queue() = default;
32
33 constexpr explicit static_priority_queue(const Compare& compare) : m_Compare{compare} {}
34
35 constexpr static_priority_queue(std::initializer_list<T> l)
36 : m_Q{make_Q(l, Compare{})}
37 , m_End{l.size()}
38 {}
39
40 constexpr static_priority_queue(std::initializer_list<T> l, const Compare& compare)
41 : m_Q{make_Q(l, compare)}
42 , m_End{l.size()}
43 , m_Compare{compare}
44 {}
45
46 constexpr static_priority_queue(const static_priority_queue&) = default;
47 constexpr static_priority_queue(static_priority_queue&&) noexcept = default;
48
49 ~static_priority_queue() = default;
50
51 constexpr static_priority_queue& operator=(const static_priority_queue&) = default;
52 constexpr static_priority_queue& operator=(static_priority_queue&&) noexcept = default;
53
54 constexpr void push(const T& val)
55 {
56 if(m_End == MaxDepth)
57 throw std::logic_error("Attempting to exceed max priority_queue depth");
58
59 m_Q[m_End++] = val;
60
61 bubble_up(m_Q.begin(), m_Q.begin() + m_End - 1, m_Compare);
62 }
63
64 [[nodiscard]]
65 constexpr const T& top() const noexcept
66 {
67 return *m_Q.begin();
68 }
69
70 constexpr void pop() noexcept
71 {
72 std::ranges::iter_swap(m_Q.begin(), m_Q.begin() + m_End -1);
73 --m_End;
74 sequoia::make_heap(m_Q.begin(), m_Q.begin() + m_End, m_Compare);
75 }
76
77 [[nodiscard]]
78 constexpr bool empty() const noexcept
79 {
80 return m_End == 0;
81 }
82
83 [[nodiscard]]
84 constexpr std::size_t size() const noexcept
85 {
86 return m_End;
87 }
88
89 [[nodiscard]]
90 friend constexpr bool operator==(const static_priority_queue& lhs, const static_priority_queue& rhs) noexcept
91 {
92 return (lhs.m_End == rhs.m_End) && std::ranges::equal(lhs.m_Q.begin(), lhs.m_Q.begin() + lhs.m_End, rhs.m_Q.begin(), rhs.m_Q.begin() + rhs.m_End);
93 }
94 private:
95 std::array<T, MaxDepth> m_Q{};
96
97 std::size_t m_End{};
98
99 SEQUOIA_NO_UNIQUE_ADDRESS Compare m_Compare;
100
101 constexpr static std::array<T, MaxDepth> make_Q(std::initializer_list<T> l, const Compare& compare)
102 {
103 auto q{utilities::to_array<T, MaxDepth>(l)};
104 sequoia::make_heap(q.begin(), q.end(), compare);
105
106 return q;
107 }
108 };
109}
A collection of constexpr algorithms.
Utility to convert an initializer_list into an array, potentially transforming the initializer_list i...
A priority_queue suitable for constexpr contexts.
Definition: StaticPriorityQueue.hpp:29