gpt4 book ai didi

c++ - std::vector 元素是否保证是连续的?

转载 作者:IT老高 更新时间:2023-10-28 11:55:17 39 4
gpt4 key购买 nike

我的问题很简单:std::vector 元素是否保证是连续的?换句话说,我可以将指向 std::vector 的第一个元素的指针用作 C 数组吗?

如果我没记错的话,C++ 标准并没有做出这样的保证。但是,std::vector 要求是,如果元素不连续,几乎不可能满足这些要求。

有人可以澄清一下吗?

例子:

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 标准当然会包含这一要求。

来自 n2798(C++0x 草案):

23.2.6 Class template vector [vector]

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().

关于c++ - std::vector 元素是否保证是连续的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/849168/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com