问题
When using Visual Studio, I can write a container traversal in at least the following three ways. Which way is preferable? Assuming:
vector<CString> strings1;
Method 1 (using the for_each
algorithm with a lambda:
for_each(strings1.begin(), strings1.end(), [](CString s){
_tprintf(_T("%s"), s);
}
Method 2 (using for each, in
, microsoft specific):
for each(auto s in strings1)
{
_tprintf(_T("%s"), s);
}
Method 3 (treat the vector with array syntax):
for (int i=0; i<v.size(); ++i)
{
_tprintf(_T("%s"), v[i]);
}
I am aware that method 2 is not portable, but I don't care about being portable. This only needs to work in Windows.
回答1:
As Stephan T. Lavavej pointed out just a couple of days ago at the "GoingNative 2012" conference, the "official" range-based for loop will be part of the soon-to-be-released beta version of the new Visual Studio. So this will be the way to go:
for(auto s : strings1)
{
_tprintf(_T("%s"), s);
}
or use a reference to reduce copying effort for the by-value use:
for (auto &s : strings1) ....
Edit: the GoingNative talk mentioned above can be found here
回答2:
In C++11 you can use range based for which is similar to method 2, but standard.
http://www2.research.att.com/~bs/C++0xFAQ.html#for
回答3:
While I think the syntax of the second option is clearer, I'd personally prefer to avoid it since it's based on an earlier version of the draft standard and hence seems liable to change in the future. YMMV though since it's mostly a question of taste.
来源:https://stackoverflow.com/questions/9182879/which-is-preferable-for-each-in-or-for-each