Function reserve()
simply allocates a contiguous region of memory big enough to hold the number of items you specify and moves the vector's old content into this new block, which makes sure no more reallocations for the vectors' storage will be done upon insertions as long as the specified capacity is not exceeded. This function is used to reduce the number of reallocations (which also invalidate iterators), but does not insert any new items at the end of your vector.
From the C++11 Standard, Paragraph 23.3.6.3/1 about reserve()
:
A directive that informs a vector of a planned change in size, so that it can manage the storage
allocation accordingly. After reserve()
, capacity()
is greater or equal to the argument of reserve if reallocation happens; and equal to the previous value of capacity()
otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve()
. If an exception is thrown other than by the move constructor of a non-CopyInsertable
type, there are no effects.
Notice that by doing prob.cols[i].push_back(idx, value);
you are likely to get undefined behavior, since i
is probably an out-of-bounds index.
On the other hand, function resize()
does insert items at the end of your vector, so that the final size of the vector will be the one you specified (this means it can even erase elements, if you specify a size smaller than the current one). If you specify no second argument to a call to resize()
, the newly inserted items will be value-initialized. Otherwise, they will be copy-initialized from the value you provide.
From the C++11 Standard, Paragraph 23.3.6.3/9 about resize()
:
If sz <= size()
, equivalent to erase(begin() + sz, end())
;. If size() < sz
, appends
sz - size()
value-initialized elements to the sequence.
So to sum it up, the reason why accessing your vector after invoking resize()
gives the expected result is that items are actually being added to the vector. On the other hand, since the call to reserve()
does not add any item, subsequent accesses to non-existing elements will give you undefined behavior.