|
| 1 | +/* |
| 2 | + * tev -- the EDR viewer |
| 3 | + * |
| 4 | + * Copyright (C) 2025 Thomas Müller <contact@tom94.net> |
| 5 | + * |
| 6 | + * This program is free software: you can redistribute it and/or modify |
| 7 | + * it under the terms of the GNU General Public License as published by |
| 8 | + * the Free Software Foundation, either version 3 of the License. |
| 9 | + * |
| 10 | + * This program is distributed in the hope that it will be useful, |
| 11 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + * GNU General Public License for more details. |
| 14 | + * |
| 15 | + * You should have received a copy of the GNU General Public License |
| 16 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | + */ |
| 18 | + |
| 19 | +#pragma once |
| 20 | + |
| 21 | +#include <algorithm> |
| 22 | +#include <stdexcept> |
| 23 | +#include <utility> |
| 24 | +#include <vector> |
| 25 | + |
| 26 | +namespace tev { |
| 27 | + |
| 28 | +template <typename T, typename Cmp = std::less<T>> class PriorityQueue { |
| 29 | + std::vector<T> mData; |
| 30 | + Cmp mCmp; |
| 31 | + |
| 32 | +public: |
| 33 | + explicit PriorityQueue(Cmp cmp = Cmp{}) : mCmp{cmp} {} |
| 34 | + |
| 35 | + template <typename Iter> PriorityQueue(Iter first, Iter last, Cmp cmp = Cmp{}) : mData{first, last}, mCmp{cmp} { |
| 36 | + std::make_heap(mData.begin(), mData.end(), mCmp); |
| 37 | + } |
| 38 | + |
| 39 | + void push(const T& val) { |
| 40 | + mData.push_back(val); |
| 41 | + std::push_heap(mData.begin(), mData.end(), mCmp); |
| 42 | + } |
| 43 | + |
| 44 | + void push(T&& val) { |
| 45 | + mData.push_back(std::move(val)); |
| 46 | + std::push_heap(mData.begin(), mData.end(), mCmp); |
| 47 | + } |
| 48 | + |
| 49 | + T pop() { |
| 50 | + if (mData.empty()) { |
| 51 | + throw std::runtime_error{"pop from empty queue"}; |
| 52 | + } |
| 53 | + |
| 54 | + std::pop_heap(mData.begin(), mData.end(), mCmp); |
| 55 | + T val = std::move(mData.back()); |
| 56 | + mData.pop_back(); |
| 57 | + return val; |
| 58 | + } |
| 59 | + |
| 60 | + const T& top() const & { return mData.front(); } |
| 61 | + T& top() & { return mData.front(); } |
| 62 | + |
| 63 | + bool empty() const { return mData.empty(); } |
| 64 | + std::size_t size() const { return mData.size(); } |
| 65 | +}; |
| 66 | + |
| 67 | +} // namespace tev |
0 commit comments