是基于环路的有益于性能吗? [英] Is the ranged based for loop beneficial to performance?

查看:88
本文介绍了是基于环路的有益于性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里阅读各种问题Stack  C ++迭代器溢出和性能**,我开始想知道是否(auto& elem:container)编译成最好的版本? (类似 auto 的种类,编译器立即推断出正确的类型,因此从不慢,有时更快)。



**例如,如果你写

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

>

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

解决方案

$ / code>



div>

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


基于范围的语句形式

  for(for-range-declaration:expression)语句

let range-init等同于括号中的表达式

 (expression)

形式

  for(for-range-declaration:braced-init-list)语句

let range-init等同于braced-init-list。在每种情况下,基于范围的 for 语句等同于

  {
auto&&& __range = range-init;
for(auto __begin = begin-expr,
__end = end-expr;
__begin!= __end;
++ __ begin)
{
-range-declaration = * __ begin;
语句
}
}


因此,是的,标准保证实现最好的形式。



对于一些容器,如 c $ c>,它是UB在此迭代过程中修改(插入/删除)。


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)

or

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

for non-invalidating containers?

解决方案

The Standard is your friend, see [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
  }
}

So yes, the Standard guarantees that the best possible form is achieved.

And for a number of containers, such as vector, it is UB to modify (insert/erase) them during this iteration.

这篇关于是基于环路的有益于性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆