Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 range-based for loops without loop variable

Tags:

c++

c++11

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.

like image 467
nonagon Avatar asked Jul 17 '13 22:07

nonagon


People also ask

Does C have range-based for loops?

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.

How do you use a range-based loop?

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

Do you need a variable for a for loop?

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.

What is ranged for loop?

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.


1 Answers

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

like image 145
sehe Avatar answered Oct 19 '22 02:10

sehe