std :: for_each的优点for循环 [英] Advantages of std::for_each over for loop
问题描述
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屋!