std::vector 元素保证是连续的吗?
虽然 C 98 标准没有明确保证 std 中的连续元素: :vector,std::vector 的要求使得元素不太可能不连续。不过,后来这在 C 0x 标准的 n2798 草案中被澄清为一项要求。
即将推出的 C 0x 标准包括以下要求:
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 第一个元素的指针作为 C 数组,如下例所示:
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 中 `std::vector` 的元素存储保证是连续的吗?的详细内容。更多信息请关注PHP中文网其他相关文章!