Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a short way to write for i in range(100) in C++?

If I got that right I can use this to iterate over a fixed range:

for(int i: {1, 2, 3, 4, 5})
    do_sth(i);

And this is the same thing:

vector<int> v{1, 2, 3, 4, 5};
for(int i: v)
    do_sth(i);

But what if I want to iterate over the range of 1, ..., 100 and already know that at compile time? What is the most beautiful way to do that? What the most efficient? What the shortest?

Edit: of course I could write a regular for loop, but the actual use case would involve more complicated content than ints.

I just oversimplified the example a bit.

like image 400
black_puppydog Avatar asked Sep 18 '13 12:09

black_puppydog


People also ask

What is a ranged based for loop?

Range-based for loop (since C++11) Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

How do you define a range in CPP?

Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .


1 Answers

for( int i = 1; i <= 100; ++i )
{
    do_sth( i );
}

?

like image 200
Kiril Kirov Avatar answered Sep 28 '22 05:09

Kiril Kirov