Home >Backend Development >C++ >Are std::vector Elements Guaranteed to Be Contiguous in Memory?
Can I Treat std::vector Elements as Contiguous Arrays?
The question arises whether the elements within a std::vector are guaranteed to occupy contiguous memory addresses, allowing us to treat its pointer to the first element as a C-array.
Historical Context:
In the C 98 standard, this guarantee was absent. Nevertheless, the standard's requirements for std::vector made it unlikely that elements would be non-contiguous.
Current Standard:
However, this matter was clarified in the C 0x (later renamed to C 11) standard. According to the TR that amended the C 98 standard: "The elements of a vector are stored contiguously." This means that for a vector of type other than bool, the following holds true:
&v[n] == &v[0] + n
where:
Example:
As a result, the following code is now valid and will function as expected:
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 Are std::vector Elements Guaranteed to Be Contiguous in Memory?. For more information, please follow other related articles on the PHP Chinese website!