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?
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.
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() .
Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression.
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.
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