远程循环与文字列表? [英] Ranged for loop with literal list?
问题描述
$ $ $ $ $ $ $ $ $ $ int int [] = {1,5, 6,2,9};
for(int n:ns){
...
}
for(int n:{1,5,6,2,9}){ / VC ++ 11拒绝这种形式
...
}
$ b
是的,它是有效的。 $ b ranged-for的定义在 您的 braced-init-list 通过 [C ++ 11:6.5.4 / 1]
为我们提供了这个构造的两种语法变体。一个在:
的右侧采用表达式,另一个采用 braced-init-list em>。
$ b auto 一个
std :: initializer_list
,这是很方便的,因为这些东西可能会迭代。
<
$ p> > for(
for-range-declaration :
braced-init-list )语句
$ b 让
{
auto&& __range = range-init;
for(auto __begin = begin-expr,
__end = end-expr;
__begin!= __end;
++ __ begin){
for-range-declaration = * __开始;
statement
$ / code $ / pre
$ b $ 所以,你基本上是这么说的:
$ p> auto ns = {1,5,6,2,9};
for(int n:ns){
// ...
}
(我还没有为这里的通用引用感到困扰。) 这反过来又是等价的到:
std :: initializer_list< int> ns = {1,5,6,2,9};
for(int n:ns){
// ...
}
现在, GCC 4.8支持这个,但是,因为Visual Studio 11实际上是Visual Studio 2012年,您需要升级以赶上: 不支持初始化列表直到Visual Studio 2013 。
In C++11, is it possible to write the following
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.
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. One takes an expression on the right-hand-side of the :
, and the other takes a braced-init-list.
Your braced-init-list deduces (through auto
) to a std::initializer_list
, which is handy because these things may be iterated over.
[..] for a range-based
for
statement of the form
for (
for-range-declaration:
braced-init-list) statement
let range-init be equivalent to the braced-init-list. In each case, a range-based for statement is equivalent to
{ 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.
这篇关于远程循环与文字列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!