Since C++11 introduced the range-based for loop (range-based for in c++11), what is the neatest way to express looping over a range of integers?
Instead of
for (int i=0; i<n; ++i)
I'd like to write something like
for (int i : range(0,n))
Does the new standard support anything of that kind?
Update: this article describes how to implement a range generator in C++11: Generator in C++
To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
for loop with range() Python for loop executes a block of code or statement repeatedly for a fixed number of times. We can iterate over a sequence of numbers produced by the range() function using for loop.
Not all objects can be iterated, for example - we cannot iterate an integer, it is a singular value. The best we can do here is iterate on a range of integers using the range type which helps us iterate through all integers in the range [0, n) .
We can use a range() to simplify writing a for loop. The stop value of the range() must be specified, but we can also modify the start ing value and the step between integers in the range() .
While its not provided by C++11, you can write your own view or use the one from boost:
#include <boost/range/irange.hpp> #include <iostream> int main(int argc, char **argv) { for (auto i : boost::irange(1, 10)) std::cout << i << "\n"; }
Moreover, Boost.Range
contains a few more interesting ranges which you could find pretty useful combined with the new for
loop. For example, you can get a reversed view.
The neatest way is still this:
for (int i=0; i<n; ++i)
I guess you can do this, but I wouldn't call it so neat:
#include <iostream> int main() { for ( auto i : { 1,2,3,4,5 } ) { std::cout<<i<<std::endl; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With