C ++ 11基于范围的for循环无循环变量 [英] C++11 range-based for loops without loop variable

查看:344
本文介绍了C ++ 11基于范围的for循环无循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我需要迭代一定次数,但我不需要一个迭代变量。例如:

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实现我可以通过用一个lambda或一个命名的函数替换代码在这里,但这个问题是专门针对循环。

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.

我希望C + + 11的基于范围的for循环将有助于:

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 */
}


b $ b

但是上面给出了一个未引用的局部变量,因为我从来没有明确引用x。

but the above gives an "unreferenced local variable" since I never explicitly reference x.

我想知道是否有一个更优雅的方式编写上述for循环,以便代码不会生成未引用的局部变量警告。

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.

推荐答案

做到这一点,但我非常怀疑它会更加优雅。你在第一个循环中有什么正确的方法,限制循环变量的作用域/生命周期。

There may be a way to do it but I very much doubt it would be more elegant. What you have in that first loop is already the correct way to do it, limiting the scope/lifetime of the loop variable.

我将忽略未使用的变量warning它只是编译器的一个迹象表明,可能会错误,毕竟)或使用编译器工具(如果可用),只是关闭此时的警告。

I would simply ignore the unused variable warning (it's only an indication from the compiler that something may be wrong, after all) or use the compiler facilities (if available) to simply turn off the warning at that point.

这篇关于C ++ 11基于范围的for循环无循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆