Skip to content

Instantly share code, notes, and snippets.

@Bktero
Created December 15, 2021 09:15
Show Gist options
  • Save Bktero/78e46c9713e44fefacd960ff3121eabd to your computer and use it in GitHub Desktop.
Save Bktero/78e46c9713e44fefacd960ff3121eabd to your computer and use it in GitHub Desktop.
[C++14] Python's enumerate() in C++
#pragma once
#include <iterator>
// Inspired by / taken from:
// https://stackoverflow.com/questions/11328264/python-like-loop-enumeration-in-c
// https://www.reedbeta.com/blog/python-like-enumerate-in-cpp17/
template<typename Iterable>
auto enumerate(Iterable&& iterable) {
using Iterator = decltype(std::begin(std::declval<Iterable>()));
using T = decltype(*std::declval<Iterator>());
struct Enumerated {
std::size_t index;
T element;
};
struct Enumerator {
Iterator iterator;
std::size_t index;
auto operator!=(const Enumerator& other) const {
return iterator != other.iterator;
}
auto& operator++() {
++iterator;
++index;
return *this;
}
auto operator*() const {
return Enumerated{index, *iterator};
}
};
struct Wrapper {
Iterable& iterable;
[[nodiscard]] auto begin() const {
return Enumerator{std::begin(iterable), 0U};
}
[[nodiscard]] auto end() const {
return Enumerator{std::end(iterable), 0U};
}
};
return Wrapper{std::forward<Iterable>(iterable)};
}
#include "enumerate.hpp"
#include <vector>
#include <iostream>
int main() {
std::vector<int> data{12, 89, 654, 123, 4587, 0};
for (auto&& enumerated: enumerate(data)) {
std::cout << "index = " << enumerated.index << " element = " << enumerated.element << '\n';
}
std::cout << "*----------------------" << '\n';
for (auto&& enumerated: enumerate(data)) {
enumerated.element *= 2;
}
std::cout << "*----------------------" << '\n';
for (auto&& enumerated: enumerate(data)) {
std::cout << "index = " << enumerated.index << " element = " << enumerated.element << '\n';
}
std::cout << "*----------------------" << '\n';
// The following requires C++17 as it uses structured binding
for (auto&&[index, character]: enumerate("bonjour")) {
std::cout << "index = " << index << " element = " << character << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment