Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neatest way to loop over a range of integers

Tags:

c++

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++

like image 969
user1101674 Avatar asked Feb 26 '13 12:02

user1101674


People also ask

How do you loop through a range of numbers?

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.

Can a for loop iterate over a range of numbers?

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.

Can you iterate over integers?

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) .

Can we use range in for loop?

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() .


2 Answers

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.

like image 175
ixSci Avatar answered Sep 22 '22 10:09

ixSci


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;   } } 
like image 24
BЈовић Avatar answered Sep 24 '22 10:09

BЈовић