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 循环对性能有益吗?
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01