Since Visual Studio 2005, native C++ has had a ‘for each’ loop construct, like C# or Java. Unfortunately it is restricted to collections from the STL library, such as vector. However, it does mean you can write very neat code to iterate through such a collection:
<br />
vector<int> data(3);<br />
data[0] = 10;<br />
data[1] = 20;<br />
data[2] = 30;<br />
<br />
int total = 0;<br />
for (vector<int>::iterator vi = data.begin(); vi != data.end(); vi++)<br />
{<br />
int i = *vi;<br />
total += i;<br />
}<br />
cout << "total: " << total << endl;<br />
<br />
total = 0;<br />
for each( const int i in data )<br />
total += i;<br />
cout << "total: " << total << endl;<br />
Now we just need that making part of the C++ standard! If you are writing standard compliant code you will have to use the
for_each function [
^].