gpt4 book ai didi

c++ - 基于范围的 for 循环是否对性能有益?

转载 作者:IT老高 更新时间:2023-10-28 12:35:15 35 4
gpt4 key购买 nike

阅读 StackOverflow 上有关 C++ 迭代器和性能**的各种问题后,我开始想知道 for(auto& elem : container) 是否被编译器“扩展”为最佳版本? (有点像 auto,编译器会立即推断出正确的类型,因此不会变慢,有时会更快)。

** 比如,你写有没有关系

for(iterator it = container.begin(), eit = container.end(); it != eit; ++it)

for(iterator it = container.begin(); it != container.end(); ++it)

对于非失效容器?

最佳答案

标准是您的 friend ,请参阅 [stmt.ranged]/1

For a range-based for statement of the form

for ( for-range-declaration : expression ) statement

let range-init be equivalent to the expression surrounded by parentheses

( expression )

and for a range-based for statement of the form

for ( for-range-declaration : braced-init-list ) statement

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
}
}

所以是的,标准保证实现最佳形式。

对于许多容器,例如 vector,在此迭代期间修改(插入/删除)它们是未定义的行为。

关于c++ - 基于范围的 for 循环是否对性能有益?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10821756/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com