简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM