遍历动态向量时使用自动运动的异常行为 [英] Unusual behavior with auto while traversing a dynamic vector

查看:173
本文介绍了遍历动态向量时使用自动运动的异常行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用auto(代码附加)遍历向量。在遍历的同时,我还在后面添加了一些元素。我没有期待我的输出。

I am traversing a vector with auto ( code attached ). While traversing, I am also appending some elements at the back. I was not expecting the output that I got.

#include <iostream>
#include <vector>
using namespace std;

vector <int> dynamic_vector;

void access( )
{
    for ( auto i : dynamic_vector ) {
        if ( i == 3 ) {
            dynamic_vector.push_back( 4 );
            dynamic_vector.push_back( 5 );
        }
        cout << i << endl;
    }
}

int main() {
    dynamic_vector.push_back( 1 );
    dynamic_vector.push_back( 2 );
    dynamic_vector.push_back( 3 );
    access( );
    return 0;
}

输出:

1
2
3

我期望从1到5的所有数字将被打印。

I was expecting all numbers from 1 to 5 will get printed. I am not able to understand how traversing with auto works?

推荐答案

这是被称为基于范围的循环

6.5.4 $ 1基于范围的语句[stmt.ranged]:

6.5.4$1 The range-based for statement [stmt.ranged]:


在每种情况下,基于范围的for语句等效于

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


注意等效伪代码, __ end (和 __ begin )将只在循环开始时设置一次。在您的情况下,在上次循环的 push_back 之后,迭代器可能无效。如果是,对它们的增量和比较将取决于实现。这意味着,作为一种可能性, __ end __ begin 将保持不变,循环计数不会改变。

Note the equivalent pseudocode, __end (and __begin) will be set only once at the start of the loop. In your case, after the push_back at the last time of loop, the iterators might be invalid. If yes, the increment and comparsion on them will be implementation dependent. That means, as one of the possibilities, __end and __begin will remain the same, and loop count won't change.

这篇关于遍历动态向量时使用自动运动的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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