将向量转换为数组 - 是否有一个“标准”的方法来做到这一点? [英] Converting a vector to an array - Is there a 'standard' way to do this?
问题描述
我知道你可以做:& theVector [0]
,但是这个标准吗?
I know you can just do: &theVector[0]
, but is this standard? Is this behavior always guaranteed?
如果没有,是否有更好的,更简单的方法?
If not, is there a better, less 'hackish' way to do this?
推荐答案
是的,这种行为是有保证的。虽然我不能引用它,但该标准保证向量元素被连续存储在内存中以允许这样。
Yes, that behavior is guaranteed. Although I can't quote it, the standard guarantees that vector elements are stored consecutively in memory to allow this.
有一个例外:
它不适用于向量< bool>
,因为模板特殊化。
It will not work for vector<bool>
because of a template specialization.
http://en.wikipedia.org/wiki / Sequence_container_%28C%2B%2B%29#Specialization_for_bool
此专业化尝试通过打包 bools
在一个位字段中。但是,它破坏了一些语义,因此,向量< bool>
上的& theVector [0]
This specialization attempts to save memory by packing bools
together in a bit-field. However, it breaks some semantics and as such, &theVector[0]
on a vector<bool>
will not work.
无论如何,向量< bool>
广泛地被认为是一个错误,所以替代方法是使用 std :: deque< bool>
。
In any case, vector<bool>
is widely considered to be a mistake so the alternative is to use std::deque<bool>
instead.
这篇关于将向量转换为数组 - 是否有一个“标准”的方法来做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!