How do I initialize a valarray from a vector?

2.7k views Asked by At

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.

1

There are 1 answers

2
jrok On

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.