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

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

问题描述

我正在用 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?

推荐答案

这叫做 基于范围的 for 循环.

6.5.4$1 基于范围的for语句[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.

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

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