What is the easiest way to do cycles in c ++ like in python?
for i in range(10): #or range(4, 10, 2) etc
foo(i)
I mean something simple and one-line like this
for(auto i: range(10)) //or range(4, 10, 2) or range(0.5, 1.0, 0.1) etc
foo(i);
but not like this:
std::vector<int> v(10);
std::iota(begin(v), end(v), 0);
for(auto i: v) {
foo(i);
}
Or this
for(auto i: []{vector<size_t> v(10); return iota(begin(v), end(v), 0), v;}() ) {
foo(i);
}
Of course, it is not difficult to use these examples or just for(;;)
but I hope there is a way to do it briefly and succinctly in python.
A Python-like
range
notion is not provided out-of-the-box, but you could roll your ownRange
class with a simple iterator, like this:In order to support range-based
for
, an iterator type andbegin()
/end()
functions will do the job. (Of course my implementation above is quick and dirty, and could probably be improved.)You will not get around rolling your own class like that, but once you have it, the usage is very much akin to the Python approach:
The example outputs (see live version here):
If you only need integer ranges, you can also use
boost::irange
(thanks to Yakk for the reminder).