Click here to Skip to main content
12,450,855 members (46,361 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

23.5K views
3 bookmarked
Posted

For each loop in Native C++

, 28 Apr 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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:


vector<int> data(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;

//instead of this
int total = 0;
for (vector<int>::iterator vi = data.begin(); vi != data.end(); vi++)
{
    int i = *vi;
    total += i;
}
cout << "total: " << total << endl;

// do this:
total = 0;
for each( const int i in data )
    total += i;
cout << "total: " << total << endl;



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)

Share

About the Author

Keith Barrett
Software Developer (Senior) Imagine Communications
United Kingdom United Kingdom
I have been working in IT for 40 years, 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.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Generalfor each will part of the C++ standard... Pin
Aescleal25-May-10 1:50
memberAescleal25-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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160826.1 | Last Updated 28 Apr 2010
Article Copyright 2010 by Keith Barrett
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid