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
...
}
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 astd::initializer_list
, which is handy because these things may be iterated over.So, you are basically saying:
(I haven't bothered with the universal reference here.)
which in turn is more-or-less equivalent to:
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 is possible to use this construction with an initializer list. Simply it seems the MS VC++ you are using does not support it.
Here is an example
You have to include header
<initializer_list>
because the initializer list in the for statement is converted tostd::initializer_list<int>