I’m trying to use vector efficiently. So I reserve memory first and then use the vector. But after I try to fill the vector using [] operator, the size of vector remains zero. Why does this happen?
vector Vec;
Vec.reserve(10);
Vec[0] = 2.0;
Vec[1] = 3.0;
...
reserve()only reserves space in the backing store so subsequent pushed elements don’t have to incur a reallocation (until you exceed the reserved space). It doesn’t change the actual size of the vector though, so yourVec[0] =access is actually running off the end of the vector.You could use
if you want, and the size will be 10. Or if you want the size to only be 2 at this point, but still reserve space to avoid multiple reallocations, you could use