Could someone explain to me why this simple code:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for(auto i: v)
{
std::cout << i << ' ';
}
std::cout << std::endl;
for(auto i: v)
{
std::cout << i << ' ';
v.push_back(4);
}
std::cout << std::endl;
for(auto i: v)
{
std::cout << i << ' ';
}
}
Code posted here: http://cpp.sh/5kxdu
Outputs:
0 1 2 3 4 5
0 0 2 3 4 5
0 1 2 3 4 5 4 4 4 4 4 4
While I would expect:
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5 4 4 4 4 4 4
I know it's bad to modify the vector during the for
loop (was just trying something else when I hit this). After v
declaration, v.capacity()
returns 6
and obviously, adding v.reserve(12)
after v
is declared fixes the issue. There is definitely something related to the vector reallocating itself to expand its capacity during the push_back
operation.
But I'm wondering if that's just an undetermined behaviour and I was just lucky that only the second element was wrong or if this is something predictable and explainable (considering how the for
loop works).