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 循环对性能有益吗?
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01