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>);