I the below code demonstrates strange behaviour when trying to access an out-of-range index in a vector
#include <iostream>
#include <vector>
int main()
{
std::vector<int> a_vector(10, 0);
for(int i = 0; i < a_vector.size(); i++)
{
std::cout << a_vector[i] << ", ";
}
for(int j = 0; j <= a_vector.size(); j++)
{
std::cout << a_vector[i] << ", ";
}
return 0;
}
The first for loop produces the expected 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
output, however the second loop produces 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1318834149,
.
The last number produced by the second loop changes every time to code is run, and is always large, unless the length of the vector is between three and seven (inclusive), in which case the last number is 0. It also persists for larger indexes - for example modifying the stop value of the second loop to j <= a_vector.size() + 2000
keeps producing large numbers until index 1139, at which point it reverts to 0.
Where does this number come from, does it mean anything, and most importantly why isn't the code throwing an 'out of range' error, which is what I would expect it to do when asked the access the 11th element of a vector 10 elements long