Advantages of std::for_each over for loop(std::for_each 优于 for 循环的优点)
问题描述
std::for_each有什么优势吗?a> 超过 for 循环?对我来说,std::for_each 似乎只会阻碍代码的可读性.为什么有些编码标准推荐使用它?
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?
推荐答案
C++11(以前称为 C++0x),就是这个令人厌烦的争论将得到解决.
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);
}
或者这个
for_each(collection.begin(), collection.end(), [](Element& e)
{
foo(e);
});
当基于范围的for循环语法可用时:
when the range-based for loop syntax is available:
for(Element& e : collection)
{
foo(e);
}
这种语法在 Java 和 C# 中已经有一段时间了,实际上,在每个最近的 Java 中,foreach 循环比经典的 for 循环更多我看到的 C# 代码.
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 循环的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::for_each 优于 for 循环的优点
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
