Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to the range-based `enumerate` loop from python in modern C++?

Is there an equivalent to the range-based enumerate loop from python in C++? I would imagine something like this.

enumerateLoop (auto counter, auto el, container) {
    charges.at(counter) = el[0];
    aa.at(counter) = el[1];
}

Can this be done with templates or macros?

I'm aware that I can just use an old school for-loop and iterate until I reach container.size(). But I'm interested how this would be solved using templates or macros.

EDIT

I played a bit with boost iterators after the hint in the comments. I got another working solution using C++14.

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);
} 

https://gist.github.com/kain88-de/fef962dc1c15437457a8

like image 820
Max Linke Avatar asked Feb 27 '15 15:02

Max Linke


1 Answers

Enumeration of multiple variables has been an idiom since C. The only complication is that you can't declare both variables in the initializer of the for loop.

int index;
for (auto p = container.begin(), index = 0; p != container.end(); ++p, ++index)

I don't think it gets any simpler (or more powerful) than that.

like image 153
QuestionC Avatar answered Sep 23 '22 14:09

QuestionC