-
Notifications
You must be signed in to change notification settings - Fork 79
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
49a1bf3
commit 8399813
Showing
4 changed files
with
44 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
// https://www.reedbeta.com/blog/python-like-enumerate-in-cpp17/ | ||
// std::vector<Thing> things; | ||
// ... | ||
// for (auto [i, thing] : enumerate(things)) | ||
// { | ||
// .. `i` gets the index and `thing` gets the Thing in each iteration | ||
// } | ||
|
||
#include <tuple> | ||
|
||
template <typename T, typename TIter = decltype(std::begin(std::declval<T>())), | ||
typename = decltype(std::end(std::declval<T>()))> | ||
constexpr auto enumerate(T &&iterable) | ||
{ | ||
struct iterator | ||
{ | ||
size_t i; | ||
TIter iter; | ||
bool operator!=(const iterator &other) const { return iter != other.iter; } | ||
void operator++() | ||
{ | ||
++i; | ||
++iter; | ||
} | ||
auto operator*() const { return std::tie(i, *iter); } | ||
}; | ||
struct iterable_wrapper | ||
{ | ||
T iterable; | ||
auto begin() { return iterator{0, std::begin(iterable)}; } | ||
auto end() { return iterator{0, std::end(iterable)}; } | ||
}; | ||
return iterable_wrapper{std::forward<T>(iterable)}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters