From e520b464e4610ca4caa8825f180e69e82c6bc943 Mon Sep 17 00:00:00 2001 From: lisyarus Date: Wed, 30 Sep 2020 07:23:05 +0300 Subject: [PATCH] Add util::array iterators over range of indices --- libs/util/include/psemek/util/array.hpp | 73 +++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/libs/util/include/psemek/util/array.hpp b/libs/util/include/psemek/util/array.hpp index 6a799d42..e8bf74b7 100644 --- a/libs/util/include/psemek/util/array.hpp +++ b/libs/util/include/psemek/util/array.hpp @@ -96,6 +96,10 @@ namespace psemek::util void fill(T const & value); + auto index_begin() const; + auto index_end() const; + auto indices() const; + private: std::unique_ptr data_; std::array dims_; @@ -148,6 +152,75 @@ namespace psemek::util return false; } + template + struct array_index_iterator + { + std::array idx; + std::array dims; + + bool end; + + std::array const & operator*() const { return idx; } + + array_index_iterator & operator ++() + { + end = next(idx, dims); + return *this; + } + }; + + struct array_index_iterator_sentinel + {}; + + template + bool operator == (array_index_iterator const & it, array_index_iterator_sentinel) + { + return it.end; + } + + template + bool operator != (array_index_iterator const & it, array_index_iterator_sentinel) + { + return !it.end; + } + + template + struct array_index_range + { + std::array dims; + + array_index_iterator begin() const + { + std::array idx; + for (std::size_t i = 0; i < N; ++i) + idx[i] = 0; + return {idx, dims, false}; + } + + array_index_iterator_sentinel end() const + { + return {}; + } + }; + + } + + template + auto array::index_begin() const + { + return indices().begin(); + } + + template + auto array::index_end() const + { + return indices().end(); + } + + template + auto array::indices() const + { + return detail::array_index_range{dims_}; } template