[英]Ranged for loop with literal list?
In C++11, is it possible to write the following 在C ++ 11中,是否可以编写以下代码
int ns[] = { 1, 5, 6, 2, 9 };
for (int n : ns) {
...
}
as something like this 像这样
for (int n : { 1, 5, 6, 2, 9 }) { // VC++11 rejects this form
...
}
tl;dr: Upgrade your compiler for great success. tl; dr:升级您的编译器可获得巨大成功。
Yeah, it's valid. 是的,这是有效的。
The definition of ranged-for in [C++11: 6.5.4/1]
gives us two variants of syntax for this construct. [C++11: 6.5.4/1]
的range-for定义为我们提供了此构造的两种语法变体。 One takes an expression on the right-hand-side of the :
, and the other takes a braced-init-list . 一个呈现的右手侧的表达式
:
,而另一个取支撑-INIT-列表 。
Your braced-init-list deduces (through auto
) to a std::initializer_list
, which is handy because these things may be iterated over. 您的bracing-init-list推断(通过
auto
)为std::initializer_list
,这很方便,因为这些事情可能会被迭代。
[..] for a range-based
for
statement of the form[..]用于以下形式的基于范围的
for
语句
for (
for-range-declaration:
braced-init-list) statement
for (
for-range-declaration:
braced-init-list) statement
let range-init be equivalent to the braced-init-list .
让range-init等同于braced-init-list 。 In each case, a range-based for statement is equivalent to
在每种情况下,基于范围的for语句等效于
{ auto && __range = range-init; for ( auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin ) { for-range-declaration = *__begin; statement } }
[..]
[..]
So, you are basically saying: 因此,您基本上是在说:
auto ns = { 1, 5, 6, 2, 9 };
for (int n : ns) {
// ...
}
(I haven't bothered with the universal reference here.) (我在这里没有为通用参考打扰。)
which in turn is more-or-less equivalent to: 或多或少等于:
std::initializer_list<int> ns = { 1, 5, 6, 2, 9 };
for (int n : ns) {
// ...
}
Now, GCC 4.8 supports this but, since "Visual Studio 11" is in fact Visual Studio 2012, you'll need to upgrade in order to catch up: initialiser lists were not supported at all until Visual Studio 2013 . 现在, GCC 4.8支持此 ,但由于“的Visual Studio 11”其实是的Visual Studio 2012,你需要为了赶上升级: 初始化器列表不被支持 ,直到的Visual Studio 2013 。
It is possible to use this construction with an initializer list. 可以将这种构造与初始化列表一起使用。 Simply it seems the MS VC++ you are using does not support it.
简而言之,似乎您正在使用的MS VC ++不支持它。
Here is an example 这是一个例子
#include <iostream>
#include <initializer_list>
int main()
{
for (int n : { 1, 5, 6, 2, 9 }) std::cout << n << ' ';
std::cout << std::endl;
return 0;
}
You have to include header <initializer_list>
because the initializer list in the for statement is converted to std::initializer_list<int>
您必须包含头文件
<initializer_list>
因为for语句中的初始化程序列表已转换为std::initializer_list<int>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.