mercredi 6 janvier 2016

How does the compiler handle a for(auto x: x_vector) where x_vector is modified inside?

I was messing around and I came across some behavior that I found peculiar when using a for(auto x: x_vector) loop that modifies x_vector. I wanted to see, if I modified the vector I was looping over would it cause problems.

Here is the entire code I compiled and ran with no errors:

#include<iostream>
#include<vector>
int main(int argc,char* argv[]){
    std::vector<int> vec1 = {1,2,3,4,5,6};
    std::vector<int> vec2 = {2,3,4,5,6,7};
    for(auto n1: vec1){
        std::cout << "at vec1" << n << " vec2 is {";
        for(auto n2: vec2){
            std::cout << " " << n2 << " ";
            if (n<n2) vec2.push_back(n);
        }
        std::cout<< "}" << std::endl;
    }
    return 0;
 }

I expected if there was no errors I would get this as output:

at vec1 1 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 }
at vec1 2 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 }
at vec1 3 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 }
at vec1 4 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 }
at vec1 5 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 }
at vec1 6 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6 }

Where the first time the inner loop is executed (n1 =1) there is a 1 appended to the end of vec 2 for each element already there before the loop gets to that part of the vector so it finishes by printing the 6 1's which are not less than 1 and then goes to the next element of vec1, so on so fourth...

Instead I got this:

at vec1 1 vec2 is { 2 3 4 5 6 7 }
at vec1 2 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 }
at vec1 3 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 }
at vec1 4 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 }
at vec1 5 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 }
at vec1 6 vec2 is { 2 3 4 5 6 7 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 }

Where it appears that the 1's added to the end of v2 on the first pass do not "appear" until the second and the 6's added on the last pass do not appear at all.

Can someone explain this behavior? I don't really understand what is going on or why this even compiled if there is somehow a delay in the modification of the vector in the inner loop.

Aucun commentaire:

Enregistrer un commentaire