Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

For each loop in Native C++

, 28 Apr 2010
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) Harris
United Kingdom United Kingdom
Keith has been working in IT for over 34 years, and has extensive experience of designing and implementing software systems. He has managed various development teams which have ranged in size from two to fifteen people. He was the Software Architect for a commercially available product. He has also conducted training courses, presented seminars, demonstrated software to potential clients, and liaised with both customers and suppliers.

Comments and Discussions

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

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web04 | 2.8.140916.1 | Last Updated 28 Apr 2010
Article Copyright 2010 by Keith Barrett
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid