std :: for_each的优点for循环 [英] Advantages of std::for_each over for loop

查看:153
本文介绍了std :: for_each的优点for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: for_each 有任何优点吗? code> for loop?对我来说, std :: for_each 似乎只会阻碍代码的可读性。为什么一些编码标准推荐它的使用?

解决方案

C ++ 11 (以前称为C ++ 0x)是这个令人讨厌的辩论会得到解决。



我的意思是,没有人在他们的心中,想要迭代整个集合,仍然会使用

  for(auto it = collection.begin(); it!= collection.end(); ++ it)
{
foo(* it);
}

  for_each(collection.begin(),collection.end(),[](Element& e)
{
foo(e);
} ); $ 时,

> loop 语法:

  for(Element& e:collection)
{
foo(e);
}

这种语法在Java和C#并且实际上有更多的 foreach 循环比古典 for 循环在我最近看到的每个Java或C#代码。 p>

Are there any advantages of std::for_each over for loop? To me, std::for_each only seems to hinder the readability of code. Why do then some coding standards recommend its use?

解决方案

The nice thing with C++11 (previously called C++0x), is that this tiresome debate will be settled.

I mean, no one in their right mind, who wants to iterate over a whole collection, will still use this

for(auto it = collection.begin(); it != collection.end() ; ++it)
{
   foo(*it);
}

Or this

for_each(collection.begin(), collection.end(), [](Element& e)
{
   foo(e);
});

when the range-based for loop syntax is available:

for(Element& e : collection)
{
   foo(e);
}

This kind of syntax has been available in Java and C# for some time now, and actually there are way more foreach loops than classical for loops in every recent Java or C# code I saw.

这篇关于std :: for_each的优点for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆