How do I initialize a valarray from a vector?

2019-07-04 16:46发布

问题:

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:

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.