std::vector<int> vecY;
vecY.reserve(2);
vecY[0] = 1;
vecY[1] = 2;
This code is wrong and evokes Undefined Behavior1. When you reserve
a vector
, you set the capacity
, not the size
.
You need to either push_back
, or construct the vector
as you did in example 1.
"Undefined Behavior" : This invokes Undefined Behavior because of the out-of-range call to operator[]
If you call vector::operator[n]
where n > vec.size()
, the behavior is Undefined.