Question

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.clear();
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?

Was it helpful?

Solution

std::vector<double>(n).swap(vec);

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.);
vec.shrink_to_fit();

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.

OTHER TIPS

std::vector<double>(n).swap(vec);

This has the advantage of actually compacting your vector too. (In your first example, clear() does not guarantee to compact your vector.)

Well let's round out the ways to do this :)

vec.swap(std::vector<double>(n));
std::vector<double>(n).swap(vec);
std::swap(vector<double>(n), vec);
std::swap(vec, vector<double>(n));

Neither of the code snippets that you posted do any memory deallocation, so they are roughly equal.

The swap trick that everyone else keeps posting will take longer to execute, because it will deallocate the memory originally used by the vector. This may or may not be desirable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top