From e928da17afa9398080ab01fe4f19f4d2f2f215db Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 12 Aug 2023 23:16:31 +0200 Subject: [PATCH] chore(cpp): introduce data structures mainly wrappers around heaps for now Signed-off-by: Matej Focko --- .common/cpp/skeleton.cpp | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/.common/cpp/skeleton.cpp b/.common/cpp/skeleton.cpp index 72e96c9..87b3b8d 100644 --- a/.common/cpp/skeleton.cpp +++ b/.common/cpp/skeleton.cpp @@ -47,6 +47,52 @@ using i64 = std::int64_t; using u64 = std::uint64_t; #pragma endregion /* aliases */ +#pragma region data structures +template +struct max_heap { + using container = std::vector; + + typename container::size_type size() const { return h.size(); } + + void push(T item) { + h.push_back(item); + std::push_heap(h.begin(), h.end()); + } + + T pop() { + std::pop_heap(h.begin(), h.end()); + T item = std::move(h.back()); + h.pop_back(); + return item; + } + + private: + container h; +}; + +template +struct min_heap { + using container = std::vector; + + typename container::size_type size() const { return h.size(); } + + void push(T item) { + h.push_back(item); + std::push_heap(h.begin(), h.end(), std::greater<>{}); + } + + T pop() { + std::pop_heap(h.begin(), h.end(), std::greater<>{}); + T item = std::move(h.back()); + h.pop_back(); + return item; + } + + private: + container h; +}; +#pragma endregion /* data structures */ + #pragma region debug void dbg_out() { std::cerr << std::endl; } template