Setting std::vector contents directly using operator []

c++, std, stl

Solution

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.

Problem

I notice that if I do `vec[0] = 1` with a fresh empty `std::vector<int>`, `vec.size()` remains `0`. However I can then still do `vec[0]` to retrieve my `1`. Is this in the realm of undefined behavior? What is going on here? Is this simply writing the `1` into reserved memory space, and I should expect this to blow up in my face, right?

Original source