Is the ranged based for loop beneficial to performance?(基于范围的 for 循环对性能有益吗?)
问题描述
在 Stack Overflow 上阅读有关 C++ 迭代器和性能的各种问题**,我开始怀疑 for(auto& elem : container) 是否被编译器扩展"为最佳版本?(有点像 auto,编译器会立即推断出正确的类型,因此永远不会变慢,有时会更快).
Reading various questions here on Stack Overflow about C++ iterators and performance**, I started wondering if for(auto& elem : container) gets "expanded" by the compiler into the best possible version? (Kind of like auto, which the compiler infers into the right type right away and is therefore never slower and sometimes faster).
** 比如你写的有没有关系
** For example, does it matter if you write
for(iterator it = container.begin(), eit = container.end(); it != eit; ++it)
或
for(iterator it = container.begin(); it != container.end(); ++it)
对于非失效容器?
推荐答案
标准是你的朋友,见[stmt.ranged]/1
The Standard is your friend, see [stmt.ranged]/1
对于表单的基于范围的语句
For a range-based for statement of the form
for ( for-range-declaration : expression ) statement
让 range-init 等价于括号括起来的表达式
let range-init be equivalent to the expression surrounded by parentheses
( expression )
以及基于范围的 for 形式的语句
and for a range-based for statement of the form
for ( for-range-declaration : braced-init-list ) statement
让 range-init 等同于花括号初始化列表.在每种情况下,基于范围的 for 语句等效于
let range-init be equivalent to the braced-init-list. In each case, a range-based for statement is equivalent to
{
auto && __range = range-init;
for ( auto __begin = begin-expr,
__end = end-expr;
__begin != __end;
++__begin )
{
for-range-declaration = *__begin;
statement
}
}
是的,该标准保证实现最佳形式.
So yes, the Standard guarantees that the best possible form is achieved.
对于许多容器,例如 vector,在此迭代期间修改(插入/擦除)它们是未定义的行为.
And for a number of containers, such as vector, it is undefined behavior to modify (insert/erase) them during this iteration.
这篇关于基于范围的 for 循环对性能有益吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于范围的 for 循环对性能有益吗?
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
