Skip to content

Instantly share code, notes, and snippets.

@kain88-de
Created March 19, 2015 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kain88-de/fef962dc1c15437457a8 to your computer and use it in GitHub Desktop.
Save kain88-de/fef962dc1c15437457a8 to your computer and use it in GitHub Desktop.
enumerate emulation in C++ with boost
#include <boost/iterator/zip_iterator.hpp>
#include <boost/range.hpp>
#include <iostream>
#include <boost/range/counting_range.hpp>
#include <list>
template <typename... T>
auto zip(const T &... containers)
-> boost::iterator_range<boost::zip_iterator<
decltype(boost::make_tuple(std::begin(containers)...))>> {
auto zip_begin =
boost::make_zip_iterator(boost::make_tuple(std::begin(containers)...));
auto zip_end =
boost::make_zip_iterator(boost::make_tuple(std::end(containers)...));
return boost::make_iterator_range(zip_begin, zip_end);
}
template <typename T> auto enumerate(const T &container) {
return zip(boost::counting_range(0, static_cast<int>(container.size())),
container);
}
int main() {
std::list<std::string> a{"a", "b", "c"};
for (auto tup : enumerate(a)) {
int i;
std::string el;
boost::tie(i, el) = tup;
std::cout << i << " " << el << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment