Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New C++11 range-for (foreach) syntax: which compilers support it?

I saw this c++11 code fragment in this BoostCon presentation by Jeremy Siek:

deque<int> topo_order;
topological_sort(g, front_inserter(topo_order));

for (int v : topo_order){ //line 39
    cout << tasks[v] << endl;
}

Upon trying to compile in gcc there is the following error:

main.cpp:39: error: expected initializer before ‘:’ token

which then got me wondering, which compilers actually support this syntax?

like image 384
shuttle87 Avatar asked Feb 17 '11 17:02

shuttle87


People also ask

Does C++ have a for each loop?

The foreach loop in C++ or more specifically, range-based for loop was introduced with the C++11. This type of for loop structure eases the traversal over an iterable data set. It does this by eliminating the initialization process and traversing over each and every element rather than an iterator.

What is a ranged based for loop?

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

What does auto do in a for loop?

Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression.


1 Answers

Well, at least GCC supports it in 4.6 (feature is called "Range-based for"). If you already have the latest version, don't forget to add the -std=c++0x option.

like image 142
AndiDog Avatar answered Oct 28 '22 02:10

AndiDog