[All]
My top 5 C++11 language features #4 - range-based for loop
By: Tim DelChiaro
Abstract: A range-based for loop basically allows a C++ developer to iterate through a collection of data and automatically provide a reference to the indexed data
This is a repost of a blog post from Embarcadero's John Thomas. You can get to his blog and the original post by clicking the blog post name below.
Following up on yesterdays discussion of the new auto keyword, my #4 top new C++11 feature is the ranged-based for loop. A range-based for loop basically allows a C++ developer to iterate through a collection of data and automatically provide a reference to the indexed data. Let’s take a look at the example of iterating through a vector of ints from yesterday.
for(auto fi = vi.begin(); fi != vi.end(), ++fi)
{
auto i = *fi;
std::cout << i;
}
As we learned yesterday, using auto really simplifies the code needed to iterate through an STL container but notice that we still need to check our ranges, increment the iterator, and de-reference the iterator to obtain the indexed content.
Well a ranged-based for loop makes this code even more succinct. Here is the equivalent code snippet to accomplish the same as the above:
for(auto i : vi)
std::cout << i;
So the range-based for loop manages the range checking, incrementing, and de-referencing in one expression. Nice!
~/jt
Connect with Us