tags:

views:

277

answers:

4

Hi all,

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?

+6  A: 
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.)

Chris Jester-Young
You could had that resize() doesn't shrink the vector capacity either.
Luc Touraille
True, sorry I took that for granted (since I see clear() as a special case of resize()). :-)
Chris Jester-Young
This is non-standard C++ - swap takes a non-const reference which won't bind to the temporary vector. Visual C++ allows this as a language extension.
James Hopkin
Tried it, but this failed to compile, due to the reason James Hopkin indicated.
andreas buykx
Thanks for the correction! :-)
Chris Jester-Young
+6  A: 
std::vector<double>(n).swap(vec);

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

James Hopkin
Thanks for your correction---I've updated my entry too. :-)
Chris Jester-Young
A: 

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));
Matt Price
The last two don't have the desired effect, at least under the default implementation of std::swap. :-)
Chris Jester-Young
Actually it does :) std::swap is overloaded in vector and calls the member function. This is required by the standard.
Matt Price
+1  A: 

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.

bk1e