Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ranged for loop with literal list?

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
   ...
}
like image 276
Thomas Eding Avatar asked Feb 10 '14 22:02

Thomas Eding


People also ask

What is ranged based for loop?

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.

Are range-based for loops faster?

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.

Does C++ have range function?

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() .


1 Answers

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>

like image 120
Vlad from Moscow Avatar answered Oct 11 '22 16:10

Vlad from Moscow