Skip to content

Instantly share code, notes, and snippets.

@jeremy-rifkin
Created March 26, 2021 01:30
Show Gist options
  • Save jeremy-rifkin/47dcad75b4556f2790aacc4319ef238b to your computer and use it in GitHub Desktop.
Save jeremy-rifkin/47dcad75b4556f2790aacc4319ef238b to your computer and use it in GitHub Desktop.
C++ python-like enumerate
template<typename T> class enumerate {
T& iteratable;
public:
enumerate(T& iteratable) : iteratable(iteratable) {}
template<typename I> class iterator {
I it;
int i = 0;
public:
iterator(I it) : it(it) {}
iterator operator++() { let i = *this; operator++(0); return i; }
iterator operator++(int) { it++; i++; return *this; }
std::pair<const int, decltype(*it)&> operator*() { return {i, *it}; }
bool operator==(const iterator& o) { return it == o.it; }
bool operator!=(const iterator& o) { return !operator==(o); }
};
template<typename I> class const_iterator {
I it;
int i = 0;
public:
const_iterator(I it) : it(it) {}
const_iterator operator++() { let i = *this; operator++(0); return i; }
const_iterator operator++(int) { it++; i++; return *this; }
std::pair<const int, const decltype(*it)&> operator*() const { return {i, *it}; }
bool operator==(const const_iterator& o) const { return it == o.it; }
bool operator!=(const const_iterator& o) const { return !operator==(o); }
};
decltype(auto) begin() { return iterator(iteratable.begin()); }
decltype(auto) end() { return iterator(iteratable.end()); }
decltype(auto) begin() const { return const_iterator(iteratable.begin()); }
decltype(auto) end() const { return const_iterator(iteratable.end()); }
};
// Example:
// std::vector<std::string> vec = {"hello", "there"};
// for(auto [i, str] : enumerate(vec)) {
// ...
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment