問題描述
在 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 循環對性能有益嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!