TermOx
priority_queue.hpp
1 #ifndef TERMOX_COMMON_PRIORITY_QUEUE_HPP
2 #define TERMOX_COMMON_PRIORITY_QUEUE_HPP
3 #include <cstdint>
4 #include <queue>
5 #include <vector>
6 
7 #include <termox/common/lockable.hpp>
8 
9 namespace ox {
10 
12 
13 template <typename T, typename Priority = std::uint8_t>
15  public:
16  using Priority_t = Priority;
17 
18  public:
20  [[nodiscard]] auto top() const -> T const& { return queue_.top().second; }
21 
23  [[nodiscard]] auto is_empty() const -> bool { return queue_.empty(); }
24 
26  [[nodiscard]] auto size() const -> std::size_t { return queue_.size(); }
27 
29  void push(Priority p, T const& x) { queue_.push(std::pair{p, x}); }
30 
32  void push(Priority p, T&& x) { queue_.push(std::pair{p, std::move(x)}); }
33 
35  auto pop() -> T
36  {
37  auto result = std::move(const_cast<T&>(this->top()));
38  queue_.pop();
39  return std::move(result);
40  }
41 
42  private:
43  using Value_t = std::pair<Priority, T>;
44 
45  private:
47  struct Compare {
48  [[nodiscard]] auto operator()(Value_t const& x, Value_t const& y) const
49  -> bool
50  {
51  return x.first < y.first;
52  }
53  };
54 
55  private:
56  using Queue_t = std::priority_queue<Value_t, std::vector<Value_t>, Compare>;
57  Queue_t queue_;
58 };
59 } // namespace ox
60 #endif // TERMOX_COMMON_PRIORITY_QUEUE_HPP
Wraps std::priority_queue to attach an int priority type to stored objects.
Definition: priority_queue.hpp:14
auto top() const -> T const &
Returns a const reference to the element with the highest priority.
Definition: priority_queue.hpp:20
auto size() const -> std::size_t
Returns the number of elements currently in the queue.
Definition: priority_queue.hpp:26
void push(Priority p, T &&x)
Move an element into the queue with the given priority.
Definition: priority_queue.hpp:32
void push(Priority p, T const &x)
Copy an element into the queue with the given priority.
Definition: priority_queue.hpp:29
auto pop() -> T
Moves top element from the queue and returns it, shrinking the queue.
Definition: priority_queue.hpp:35
auto is_empty() const -> bool
Returns true if no elements in queue.
Definition: priority_queue.hpp:23