It is indeed Undefined behavior
[]
Does not check bounds and does not add elements. What you are doing is writing to and reading from the buffer which vector
uses, but that is considered undefined behavior.
You should use one of these methods to add to vectors.
.push_back(0)
the default method - appends to the end
.resize(num,0)
resizes the vector
up (or down) to num
and sets the value of the new elements to the 2nd arg, 0.
The vector
can also be constructed with an initial size - vector(num,0)
is more or less identical to v = vector();v.resize(num,0)
On the other end, to do this safely, you can use .at(n)
to access elements, and this will throw an std::out_of_range exception if you access beyond the bounds.