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中文網其他相關文章!