如何从向量初始化valarray? [英] How do I initialize a valarray from a vector?
本文介绍了如何从向量初始化valarray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
它是确定/安全/良好的做法,写下列为了填充一个向量的
内容的valarray?
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.
推荐答案
是的,这是完全正常的。向量的内容保证是连续的(见C ++标准中的 [vector.overview],§1
)。
Yes, this is perfectly fine. The contents of vector are guaranteed to be contiguous (see [vector.overview], §1
in C++ standard).
注意,由于C ++ 11,可以直接使用初始化器列表初始化 valarray
。
Note that since C++11, you can initialize valarray
using initializer list directly.
这篇关于如何从向量初始化valarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文