My top 5 C++11 language features #4 - range-based for loop
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
Share This | Email this page to a friend
Posted by J T on November 13th, 2012 under C++, C++11, C++Builder, ISO C++ |4 Responses to “My top 5 C++11 language features #4 - range-based for loop”
Leave a Comment
You must be logged in to post a comment.


RSS Feed

November 13th, 2012 at 11:10 pm
This is really nice. I find range based loops really useful in other languages.
One point, I think your first example will not compile without brackets, because it will be out of scope when it reaches the output line.
for(auto fi = vi.begin(); fi != vi.end(), ++fi)
{
auto i = *fi;
std::cout << i;
}
November 15th, 2012 at 5:01 pm
So essentially, C++ finally got a for-in loop at the language level, now that other languages have had it for years and years?
November 19th, 2012 at 5:46 pm
Yes, C++11 finally brought this feature into the language. Typically, these types of features are first "market tested" through the Boost library and if widely adopted, becomes a candidate for either a language addition or to be brought into the STL. So, C++ developers have had this capability for years and years in Boost but now it is available at the language level (as opposed to continuing to be a library feature).
November 19th, 2012 at 5:46 pm
@Stuart Kelly - good catch - fixed.