Memory Contiguity of std::Vector Elements
Concerned developers often raise the question of whether elements within a std::vector are guaranteed to be contiguous. This property determines whether it's permissible to treat the pointer to the first element as a C-style array.
Standard Provisions
Initially, the C 98 standard neglected to specify this aspect. However, subsequent technical reports (TR) rectified this oversight, and the forthcoming C 0x standard will incorporate it as an explicit requirement.
TR Specifications
N2798, a draft of C 0x, postulates:
"A vector is a sequence container that supports random access iterators ... 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()."
Example
Based on this specification, consider the following code snippet:
std::vectorvalues; // ... 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 C standard guarantees that this code will function as intended by allowing direct memory access to the vector's elements.
The above is the detailed content of Is std::vector Element Memory Contiguous in C ?. For more information, please follow other related articles on the PHP Chinese website!