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?
You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.
To create a vector of specified data type and length in R we make use of function vector(). vector() function is also used to create empty vector. There is a very straightforward approach for this. Implementation combined with this approach paints a better picture.
Specifying a default value for the Vector: In order to do so, below is the approach: Syntax: // For declaring vector v(size, default_value); // For Vector with a specific default value // here 5 is the size of the vector // and 10 is the default value vector v1(5, 10);
You'll just need to push_back or emplace_back when you're writing into the vector after clear() ing, instead of using operator[] . To make this consistent with the first use, don't initialize your vector with 10000000 value-constructed elements, but use reserve(10000000) to pre-allocate without initialization. eg.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With