Files
Library/include/Void/Containers/PriorityQueue.hpp
T
faumarayandClaude Fable 5 28b94883fd Restructure into umbrella modules (~55 -> 16 targets)
Headers move, CMake targets merge, C++ namespaces stay unchanged:
- Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant
- Functional: Pipeline, Either, Result, Retry
- Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval
- Math: +Matrix, Numeric, Random, Histogram
- Text: Str, Format, Tokenizer, Diff, Encoding, Semver
- Data: Json, Csv, Ini
- Async: Coro, Concurrency, EventBus, Observable
- Time: +Bench
- Log: Log facade + Logging framework (facade now header-only, breaking
  the Stacktrace<->Log link cycle the merge would have created)
- System: FileSystem + Process
- Configuration: +Argparse
- Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail

Module system fixes:
- OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no
  longer depends on the alphabetical discovery order of src/ subdirs
  (Testing -> Text would have been silently dropped).
- Every header-only module now has a tracked module.cmake; previously the
  empty src/<Name> marker dirs were untracked, so a fresh clone would have
  silently skipped those modules.
- VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT.

Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files
prefixed: ResultBasic etc.). Test count verified identical (831) before and
after. README/CLAUDE.md module tables updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 18:50:02 +03:00

151 lines
4.7 KiB
C++

#pragma once
#include <cassert>
#include <cstddef>
#include <functional>
#include <optional>
#include <stdexcept>
#include <unordered_map>
#include <vector>
namespace Void::PriorityQueue
{
// ── PriorityQueue<K, P> ───────────────────────────────────────────────────────
// Indexed min-heap (by priority P) with O(log n) push/pop/update.
// K is the key type (must be hashable). P is the priority type.
// Equal priorities maintain stable-ish order (not guaranteed).
template <typename K, typename P, typename Cmp = std::less<P>>
class PriorityQueue
{
public:
explicit PriorityQueue(Cmp cmp = {}) : cmp_{cmp} {}
// Push a key with priority. If key already exists, equivalent to update().
void push(K key, P priority)
{
const auto it = index_.find(key);
if (it != index_.end()) {
heap_[it->second].priority = priority;
bubble_up(it->second);
bubble_down(it->second);
return;
}
const std::size_t i = heap_.size();
heap_.push_back({std::move(key), std::move(priority)});
index_[heap_.back().key] = i;
bubble_up(i);
}
// Returns the top (min) element without removing it.
[[nodiscard]] const K& top_key() const
{
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
return heap_[0].key;
}
[[nodiscard]] const P& top_priority() const
{
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
return heap_[0].priority;
}
// Remove and return the top key.
K pop()
{
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
K result = std::move(heap_[0].key);
index_.erase(result);
if (heap_.size() > 1) {
heap_[0] = std::move(heap_.back());
index_[heap_[0].key] = 0;
}
heap_.pop_back();
if (!heap_.empty()) bubble_down(0);
return result;
}
// Update the priority of an existing key. No-op if key not found.
void update(const K& key, P priority)
{
const auto it = index_.find(key);
if (it == index_.end()) return;
heap_[it->second].priority = std::move(priority);
bubble_up(it->second);
bubble_down(it->second);
}
// Remove a specific key. No-op if not found.
void erase(const K& key)
{
const auto it = index_.find(key);
if (it == index_.end()) return;
const std::size_t i = it->second;
index_.erase(it);
if (i == heap_.size() - 1) { heap_.pop_back(); return; }
heap_[i] = std::move(heap_.back());
index_[heap_[i].key] = i;
heap_.pop_back();
bubble_up(i);
bubble_down(i);
}
[[nodiscard]] bool contains(const K& key) const { return index_.count(key) > 0; }
[[nodiscard]] std::optional<P> priority_of(const K& key) const
{
const auto it = index_.find(key);
if (it == index_.end()) return std::nullopt;
return heap_[it->second].priority;
}
[[nodiscard]] std::size_t size() const noexcept { return heap_.size(); }
[[nodiscard]] bool empty() const noexcept { return heap_.empty(); }
void clear() { heap_.clear(); index_.clear(); }
private:
struct Entry { K key; P priority; };
std::vector<Entry> heap_;
std::unordered_map<K, std::size_t> index_;
Cmp cmp_;
void swap_entries(std::size_t i, std::size_t j)
{
index_[heap_[i].key] = j;
index_[heap_[j].key] = i;
std::swap(heap_[i], heap_[j]);
}
void bubble_up(std::size_t i)
{
while (i > 0) {
const std::size_t parent = (i - 1) / 2;
if (!cmp_(heap_[i].priority, heap_[parent].priority)) break;
swap_entries(i, parent);
i = parent;
}
}
void bubble_down(std::size_t i)
{
const std::size_t n = heap_.size();
while (true) {
std::size_t smallest = i;
const std::size_t l = 2 * i + 1, r = 2 * i + 2;
if (l < n && cmp_(heap_[l].priority, heap_[smallest].priority)) smallest = l;
if (r < n && cmp_(heap_[r].priority, heap_[smallest].priority)) smallest = r;
if (smallest == i) break;
swap_entries(i, smallest);
i = smallest;
}
}
};
// ── MaxPriorityQueue — max-heap variant ───────────────────────────────────────
template <typename K, typename P>
using MaxPriorityQueue = PriorityQueue<K, P, std::greater<P>>;
} // namespace Void::PriorityQueue