Click here to Skip to main content
15,884,032 members
Articles / Programming Languages / C++
Tip/Trick

For each loop in Native C++

Rate me:
Please Sign up or sign in to vote.
4.60/5 (5 votes)
28 Apr 2010CPOL 31.7K   3   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)


Written By
Software Developer (Senior) Imagine Communications
United Kingdom United Kingdom
I have been working in IT since 1975, in various roles from junior programmer to system architect, and with many different languages and platforms. I have written shedloads of code.

I now live in Bedfordshire, England. As well as working full time I am the primary carer for my wife who has MS. I am learning to play the piano. I have three grown up children and a cat.

Comments and Discussions

 
Generalfor each will part of the C++ standard... Pin
Aescleal25-May-10 1:50
Aescleal25-May-10 1:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.