Are std::vector Elements Guaranteed to Be Contiguous?
While the C 98 standard did not explicitly guarantee contiguous elements within a std::vector, the requirements for std::vector made it highly unlikely that the elements would not be contiguous. However, this was later clarified as a requirement in the n2798 draft of the C 0x standard.
The upcoming C 0x standard includes the following requirement:
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().
This means that you can safely use the pointer to the first element of a std::vector as a C-array, as in the following example:
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' } }
The above is the detailed content of Is `std::vector`'s Element Storage Guaranteed to Be Contiguous in C ?. For more information, please follow other related articles on the PHP Chinese website!