Created
August 28, 2024 16:30
-
-
Save slyshykO/db2137b8f103298f01eecdf92d32cbd2 to your computer and use it in GitHub Desktop.
c++ enumerate
This file contains hidden or 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
// http://reedbeta.com/blog/python-like-enumerate-in-cpp17/?fbclid=IwAR3b_OJ61ol7pU525NxcIzureSBU1emoSQtvVG3L_q_pCvBcO4yKyyHU6OA | |
#include <iostream> | |
#include <tuple> | |
#include <vector> | |
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) }; | |
} | |
int main() | |
{ | |
std::vector<int> v = {1,2,3,4,5,6,7,8,9,10}; | |
for (auto [i, thing] : enumerate(v)) | |
{ | |
std::cout << "i:" << i << "\tT:" << thing << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment