vectors in range based for loop

16,499
for(auto i : anotherVector)
    cout << anotherVector[i] << endl;

This code doesn't do what you think it does. The range-based for loop iterates over values, not over indices. In other words, the loop variable (i) is assigned all ements of the vector in turn.

To replicate the functionality of your first loop, you need this:

for (auto i : anotherVector)
    cout << i << endl;

What your original code was doing was take an element of the vector, and use it to index into the vector again. That's why the numbers were off by one (since the vector held number n + 1 at position n). Then, the final output (81 in your case) was effectively random and the result of Undefined Behaviour—you were reaching past the end of the vector.

Share:
16,499
Shiv Pratap Singh
Author by

Shiv Pratap Singh

Updated on June 04, 2022

Comments

  • Shiv Pratap Singh
    Shiv Pratap Singh almost 2 years

    I was testing vector to vector initialization, I used range based for loop it gives different output.

    with respect to Normal for loop.

    vector<int> intVector;
    
    for(int i = 0; i < 10; i++) {
        intVector.push_back(i + 1);
        cout << intVector[i] << endl;
    }
    
    cout << "anotherVector" << endl;
    
    vector<int> anotherVector(intVector);
    for(auto i : anotherVector)
        cout << anotherVector[i] << endl;
    //for(unsigned int i = 0; i < anotherVector.size(); i++) {
    //    cout << anotherVector[i] << endl;
    //}
    

    this range based for loop gives the output - Linux ubuntu

    Output

    STLTest Cunstructor Called.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    anotherVector
    2
    3
    4
    5
    6
    7
    8
    9
    10
    81
    

    2.

    vector<int> intVector;
    
    for(int i = 0; i < 10; i++) {
        intVector.push_back(i + 1);
        cout << intVector[i] << endl;
    }
    
    cout << "anotherVector" << endl;
    
    vector<int> anotherVector(intVector);
    //for(auto i : anotherVector)
    //    cout << anotherVector[i] << endl;
    for(unsigned int i = 0; i < anotherVector.size(); i++) {
        cout << anotherVector[i] << endl;
    }
    

    This gives different output.

    output

    STLTest Cunstructor Called.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    anotherVector
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    why both for loop acting differently?