每个in,for或for_each中哪个更合适? [英] Which is preferable for each, in or for_each?
问题描述
使用Visual Studio时,至少可以通过以下三种方式编写容器遍历.哪种方法更可取?假设:
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;
方法1(使用带有lambda的 for_each
算法:
Method 1 (using the for_each
algorithm with a lambda:
for_each(strings1.begin(), strings1.end(), [](CString s){
_tprintf(_T("%s"), s);
}
方法2(对于Microsoft,特定于/,分别使用):
Method 2 (using for each, in
, microsoft specific):
for each(auto s in strings1)
{
_tprintf(_T("%s"), s);
}
方法3(使用数组语法处理向量):
Method 3 (treat the vector with array syntax):
for (int i=0; i<v.size(); ++i)
{
_tprintf(_T("%s"), v[i]);
}
我知道方法2不是可移植的,但是我并不在乎是可移植的.这仅需要在Windows中工作.
I am aware that method 2 is not portable, but I don't care about being portable. This only needs to work in Windows.
推荐答案
就像斯蒂芬·拉瓦维(几天前)在"GoingNative 2012"会议上指出的那样,基于范围"的for循环将是其中的一部分新的Visual Studio即将发布的beta版本.所以这就是要走的路:
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) ....
可以在此处
这篇关于每个in,for或for_each中哪个更合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!