Yes I already used the at() operator several times.
But this problem using the [] operator occured to me, and I think it's very painful that this is not catched.
This problem occurs in a larger program, where I loop over several entries of a larger dataset, filling this vector for each entry. Before I fill the vector, I always reset it with vector.clear()
So I have to change all my calls of [] to .at() or is there a way to actually clear the vector elements properly?
Before I fill the vector, I always reset it with vector.clear()
If your intent is to deallocate the dynamic array held by the vector, clear() does not do that; it only calls the destructors of the elements in the array. Vector's destructor will deallocate it: if your vector is no longer needed, at some point, it should go out of scope and get destructed.
What you should be doing is getting the result of vector::size() and being mindful of the valid range. Alternatively, you could use the iterators in the range [vector::begin(), vector::end()).