Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(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.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?

like image 993
andreas buykx Avatar asked Oct 06 '08 11:10

andreas buykx


People also ask

How do you initialize a vector to a specific size?

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.

How do you make a vector a certain length?

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.

How do you initialize a vector by its default value?

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);

How do you reinitialize a vector?

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.


3 Answers

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.

like image 111
James Hopkin Avatar answered Nov 05 '22 05:11

James Hopkin


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.)

like image 34
Chris Jester-Young Avatar answered Nov 05 '22 05:11

Chris Jester-Young


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));
like image 33
Matt Price Avatar answered Nov 05 '22 05:11

Matt Price