As far as I know the C++ standard does not specify exactly how vector capacity is increased when vector::resize requires an increase. But is there a “typical” implementation?
Specifically: I don’t know how large my vector needs to be. Further, the elements come in random order. So for each element I have this:
if ( index >= vector.size() ) {
vector.resize ( index + 1 );
}
vector.at ( index ) = element;
If the elements come in increasing index order, will the vector capacity be increased by one for each call to resize (in a typical implementation)? I’m hoping not…
The standard makes no guarantees about the asymptotics of repeated calls to
resize(). It is entirely feasible that the container will simply grow the capacity to precisely the required target size. In fact, this would probably be the desirable behaviour (i.e. the least wasteful) in the majority of standard use cases forresize()(e.g. where it’s just used once).If you’re worried, just implement your own geometric growth: