andreas buykx andreas buykx - 1 year ago 64
C++ Question

(re)initialise a vector to a certain length with initial values

As a function argument I get a

vector<double>& vec
(an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes.

This will work

vec.resize( n, 0.0 );

And this will work as well:

vec.resize( n );
vec.assign( n, 0.0 );

Is the second more efficient (because no memory deallocation/allocation is involved)? Is there a more efficient way to do this?

Answer Source

After this, vec is guaranteed to have size and capacity n, with all values 0.0.

Perhaps the more idiomatic way since C++11 is

vec.assign(n, 0.);

with the second line optional. In the case where vec starts off with more than n elements, whether to call shrink_to_fit is a trade-off between holding onto more memory than is required vs performing a re-allocation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download