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 int
s.
I just oversimplified the example a bit.
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.
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() .
for( int i = 1; i <= 100; ++i )
{
do_sth( i );
}
?
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