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
...
}
Range-based for loop (since C++11) 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.
Advantages of the range-based for loop We can easily modify the size and elements of the container. It does not create any copy of the elements. It is much faster than the traditional for 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() .
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
#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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With