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;
}
Output:
1
2
3
I was expecting all numbers from 1 to 5 will get printed. I am not able to understand how traversing with auto works?