From d66b3d3561de127f6d995e4b0af0aaffac33d701 Mon Sep 17 00:00:00 2001 From: Eric Mertens Date: Mon, 4 Dec 2023 15:45:17 -0800 Subject: [PATCH] use a counter --- 2023/04.cpp | 6 +++--- lib/include/aocpp/Counter.hpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 lib/include/aocpp/Counter.hpp diff --git a/2023/04.cpp b/2023/04.cpp index e62afc4..0855b5e 100644 --- a/2023/04.cpp +++ b/2023/04.cpp @@ -12,6 +12,7 @@ #include #include +#include namespace { @@ -47,11 +48,10 @@ auto CountWins(std::vector& cards) -> std::vector for (auto& card : cards) { - std::vector xs; std::sort(card.mine.begin(), card.mine.end()); std::sort(card.winners.begin(), card.winners.end()); - std::set_intersection(card.mine.begin(), card.mine.end(), card.winners.begin(), card.winners.end(), std::back_inserter(xs)); - result.push_back(xs.size()); + auto const c = std::set_intersection(card.mine.begin(), card.mine.end(), card.winners.begin(), card.winners.end(), Counter{}); + result.push_back(c); } return result; diff --git a/lib/include/aocpp/Counter.hpp b/lib/include/aocpp/Counter.hpp new file mode 100644 index 0000000..e257db5 --- /dev/null +++ b/lib/include/aocpp/Counter.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include +#include + +template +struct Counter +{ + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T*; + using reference = T&; + using iterator_category = std::output_iterator_tag; + + struct EmptyRef { + auto operator=(T const&) const -> void { } + }; + + std::size_t n; + + auto operator++() -> Counter& { n++; return *this; } + auto operator++(int) -> Counter { Counter temp; n++; return temp; } + auto operator*() const -> EmptyRef { return EmptyRef{}; } + auto operator-(Counter const& rhs) const -> std::ptrdiff_t { + return std::ptrdiff_t{n} - std::ptrdiff_t{rhs.n}; + } + operator std::size_t() const { return n; } +}; + +static_assert(std::output_iterator, int>);