in 或 for_each 哪个对每个更可取?
使用Visual Studio时,我至少可以通过以下三种方式来编写容器遍历。哪种方式更可取?假设:
vector<CString> strings1;
方法 1(使用带有 lambda 的 for_each
算法:
for_each(strings1.begin(), strings1.end(), [](CString s){
_tprintf(_T("%s"), s);
}
方法 2(使用 for every, in
,微软特定):
for each(auto s in strings1)
{
_tprintf(_T("%s"), s);
}
方法 3(使用数组语法处理向量) :
for (int i=0; i<v.size(); ++i)
{
_tprintf(_T("%s"), v[i]);
}
我知道方法 2 不可移植,但我不在乎是否可移植,这只需要在 Windows 中工作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++11 中,您可以使用基于范围的方法,这与方法 2 类似,但是是标准的。
http://www2.research.att.com/~bs/C++0xFAQ。 html#for
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
正如 Stephan T. Lavavej 几天前在“GoingNative 2012”会议上指出的那样,“官方”基于范围的 for 循环将成为即将发布的新 Visual Studio 测试版的一部分。因此,这将是要走的路:
或使用参考来减少按值使用的复制工作:
编辑:可以找到上面提到的 GoingNative 谈话 此处
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:
or use a reference to reduce copying effort for the by-value use:
Edit: the GoingNative talk mentioned above can be found here
虽然我认为第二个选项的语法更清晰,但我个人更愿意避免它,因为它基于标准草案的早期版本,因此似乎将来可能会发生变化。 YMMV 不过,因为这主要是一个品味问题。
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.