From e81fe345c91a9f70b47b1d30503c0e72870ede5b Mon Sep 17 00:00:00 2001 From: Patrick Wuttke Date: Sun, 25 Jun 2023 19:38:09 +0200 Subject: [PATCH] Added enumerate() function for enumerating an iterator + index. --- source/mijin/util/iterators.hpp | 91 +++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 source/mijin/util/iterators.hpp diff --git a/source/mijin/util/iterators.hpp b/source/mijin/util/iterators.hpp new file mode 100644 index 0000000..b881bab --- /dev/null +++ b/source/mijin/util/iterators.hpp @@ -0,0 +1,91 @@ +#pragma once + +#if !defined(MIJIN_UTIL_ITERATORS_HPP_INCLUDED) +#define MIJIN_UTIL_ITERATORS_HPP_INCLUDED 1 + +#include +#include + +namespace mijin +{ +template +struct EnumeratingIterator +{ + TIdx idx; + TIterator base; + + EnumeratingIterator(TIdx idx_, TIterator base_) noexcept : idx(idx_), base(base_) {} + EnumeratingIterator(const EnumeratingIterator&) noexcept = default; + + EnumeratingIterator& operator=(const EnumeratingIterator&) noexcept = default; + + auto operator*() const noexcept + { + return std::tie(idx, *base); + } + + EnumeratingIterator& operator++() noexcept + { + ++idx; + ++base; + return *this; + } + + EnumeratingIterator operator++(int) noexcept + { + EnumeratingIterator copy(*this); + ++(*this); + return copy; + } + + EnumeratingIterator& operator--() noexcept + { + --idx; + --base; + return *this; + } + + EnumeratingIterator operator--(int) noexcept + { + EnumeratingIterator copy(*this); + --(*this); + return copy; + } + + bool operator==(const EnumeratingIterator& other) const noexcept + { + return base == other.base; // note: ignoring idx so we don't have to find it out for end() + } + + bool operator!=(const EnumeratingIterator& other) const noexcept + { + return base != other.base; // note: ignoring idx so we don't have to find it out for end() + } +}; +template +EnumeratingIterator(TIdx, TIterator) -> EnumeratingIterator; + +template +struct Enumeratable +{ + TIterable& base; + + auto begin() const noexcept + { + return EnumeratingIterator(TIdx(0), base.begin()); + } + + auto end() const noexcept + { + return EnumeratingIterator(TIdx(0), base.end()); + } +}; + +template +Enumeratable enumerate(TIterable& iterable) +{ + return {iterable}; +} +} // namespace mijin + +#endif // MIJIN_UTIL_ITERATORS_HPP_INCLUDED \ No newline at end of file