问题描述
我的问题很简单:std::vector
元素是否保证是连续的?换句话说,我可以使用指向 std::vector
第一个元素的指针作为 C 数组吗?
My question is simple: are std::vector
elements guaranteed to be contiguous? In other words, can I use the pointer to the first element of a std::vector
as a C-array?
如果我没记错的话,C++ 标准并没有做出这样的保证.但是,std::vector
的要求是,如果元素不连续,几乎不可能满足它们.
If my memory serves me well, the C++ standard did not make such guarantee. However, the std::vector
requirements were such that it was virtually impossible to meet them if the elements were not contiguous.
有人可以澄清一下吗?
示例:
std::vector<int> values;
// ... fill up values
if( !values.empty() )
{
int *array = &values[0];
for( int i = 0; i < values.size(); ++i )
{
int v = array[i];
// do something with 'v'
}
}
推荐答案
这在 C++98 标准中被遗漏,但后来作为 TR 的一部分添加.即将推出的 C++0x 标准当然会将此作为要求包含在内.
This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement.
来自 n2798(C++0x 草案):
From n2798 (draft of C++0x):
23.2.6 类模板向量[向量]
1 向量是支持随机访问迭代器的序列容器.此外,它支持(摊销)最后的恒定时间插入和擦除操作;在中间插入和擦除需要线性时间.贮存管理是自动处理的,但可以提供提示以提高效率.的元素向量是连续存储的,这意味着如果 v 是一个向量,其中 T 是其他类型比 bool,那么它遵守恒等式 &v[n] == &v[0] + n 对于所有 0 <= n <v.size().
1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
这篇关于std::vector 元素是否保证是连续的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!