In c++ 11 you can iterate over a container with range for loops :
for (auto i : vec) { /* do stuff */ }
Besides the drawback that iterating in reverse is not that obvious (C++11 reverse range-based for-loop) it is also limited by the fact that you cannot define a custom step for the iteration.
Is there a way to do it? I can't get my mind around it, but imagine an adaptor like
template<typename T>
struct step
{
T const &container;
step( T const &cont, int aStep);
// provide begin() / end() member functions
// maybe overload the ++ operator for the iterators ?
};
for (auto i : step(vec, i)) {}
EDIT:
The discussion is about achieving semantics similar to Pythons generators https://wiki.python.org/moin/Generators eg the range() function. Please don't make pointless comments on how this would increase code complexity, no one ever went back to hand written for loops in Python, and even though this is not the case in C++ (I should say that again: this is NOT the case in c++) I wanted to explore ways to write
for (auto i : range(vec, step))
since the new standard provides the facilities to use such syntax. The range() function would be a one time effort and the user of the code would not have to worry about the specifics of the imlpementation
operator++()
, do itn
times on the underlying iterator. – Casandra