Aprepro 5.0x
Loading...
Searching...
No Matches
enumerate.h
Go to the documentation of this file.
1// https://www.reedbeta.com/blog/python-like-enumerate-in-cpp17/
2// std::vector<Thing> things;
3// ...
4// for (auto [i, thing] : enumerate(things))
5// {
6// .. `i` gets the index and `thing` gets the Thing in each iteration
7// }
8
9#include <tuple>
10
11template <typename T, typename TIter = decltype(std::begin(std::declval<T>())),
12 typename = decltype(std::end(std::declval<T>()))>
13constexpr auto enumerate(T &&iterable)
14{
15 struct iterator
16 {
17 size_t i;
18 TIter iter;
19 bool operator!=(const iterator &other) const { return iter != other.iter; }
20 void operator++()
21 {
22 ++i;
23 ++iter;
24 }
25 auto operator*() const { return std::tie(i, *iter); }
26 };
27 struct iterable_wrapper
28 {
29 T iterable;
30 auto begin() { return iterator{0, std::begin(iterable)}; }
31 auto end() { return iterator{0, std::end(iterable)}; }
32 };
33 return iterable_wrapper{std::forward<T>(iterable)};
34}
constexpr auto enumerate(T &&iterable)
Definition enumerate.h:13