For each loop in Native C++






4.60/5 (5 votes)
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:
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 [^].
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 [^].