Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

For each loop in Native C++

4.60/5 (5 votes)
28 Apr 2010CPOL 1  
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:vector...
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:


C++
<br />
vector<int> data(3);<br />
data[0] = 10;<br />
data[1] = 20;<br />
data[2] = 30;<br />
 <br />
//instead of this<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 />
// do this:<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 [^].

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)