In C++ I need to iterate a certain number of times, but I don't need an iteration variable. For example:
for( int x=0; x<10; ++x ) { /* code goes here, i do not reference "x" in this code */ }
I realize I can do this by replacing "code goes here" with a lambda or a named function, but this question is specifically about for loops.
I was hoping that C++11's range-based for loops would help:
for( auto x : boost::irange(0,10) ) { /* code goes here, i do not reference "x" in this code */ }
but the above gives an "unreferenced local variable" since I never explicitly reference x.
I'm wondering if there is a more elegant way to write the above for loops so that the code does not generate an "unreferenced local variable" warning.
Range-based for loop in C++ It 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 Loop iterates each element from the list until the given range. So no need of any variable to check condition. While Loop iterates until the given condition is true.
Example 1: Ranged for Loop Using Array Note: The ranged for loop automatically iterates the array from its beginning to its end. We do not need to specify the number of iterations in the loop.
Edit now with 100% fewer loop variables declared.
template <typename F> void repeat(unsigned n, F f) { while (n--) f(); }
Use it as:
repeat(10, f);
or
repeat(10, [] { f(); });
or
int g(int); repeat(10, std::bind(g, 42));
See it live at http://ideone.com/4k83TJ
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