3

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.

4

1 回答 1

3

是的,这很好。vector 的内容保证是连续的(参见[vector.overview], §1C++ 标准)。

请注意,从 C++11 开始,您可以valarray直接使用初始化程序列表进行初始化。

于 2014-12-02T12:51:31.783 回答