Tag Archive for: Visual Studio

TIL: About Visual Studio C++ and ‘for each in’

10 Mar
March 10, 2011

Most C++ developers are familiar using with for_each() when iterating over an STL collection. But a few months ago as I read a blogĀ post about the ‘auto’ keyword over at Marc Gregoire’s Blog I was dumbstruck when saw the following example:

[sourcecode language=”cpp”]
for each (auto m in myMap)
tcout << _T("Map element ") << m.first << _T(": ");
for each(auto e in m.second)
tcout << _T("'") << e << _T("', ");
tcout << endl;

What the heck was this ‘for each’ without an underscore business? Apparently I’d been painfully unaware of this new syntax since 2004!!! It’s Microsoft/Visual Studio specific. But since my primary project is Windows-based through and through, you can bet I’ll be making use of this beauty to keep my code cleaner.


PS. Do note, though, that this syntax automatically dereferences iterators, so it’s not useful if you need to do iterator manipulation.