Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a valarray from a vector?

Is it ok/safe/good practice to write the following in order to fill a valarray with the content of a vector?

vector<int> myVect = {2,0,1,0,0,1,1,0,0,0}; // Any vector
valarray<int> myVala ( &(myVect[0]), myVect.size() );
//Edit: as suggested by Xeo, this code looks much cleaner (C++11)
valarray<int> myVala ( myVect.data(), myVect.size() );

It seems to work fine but I would like to be sure it works on any case.

like image 292
wxc3 Avatar asked Oct 21 '25 02:10

wxc3


1 Answers

Yes, this is perfectly fine. The contents of vector are guaranteed to be contiguous (see [vector.overview], §1 in C++ standard).

Note that since C++11, you can initialize valarray using initializer list directly.

like image 71
jrok Avatar answered Oct 22 '25 16:10

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!