STL Vector Contiguous Storage Assumption
Can we assume that the elements of a modified STL vector are stored contiguously in memory?
Question:
Given a resized STL vector vc
Answer:
Yes, but with a caveat.
According to the C 03 standard (23.2.4.1), elements within an STL vector are stored contiguously. This means that for any vector v with element type T (other than bool), &vc[0] n equals &vc[n] for all values of n between 0 and v.size() - 1.
Caution:
While this assumption generally holds true, it's important to be aware of potential memory reallocation that may occur when adding elements to the vector. If the vector's capacity is exceeded, the vector's data may be moved to a new memory block, invalidating any existing pointers or iterators. Therefore, it's crucial to consider the potential for reallocation when relying on this contiguous storage assumption.
The above is the detailed content of Is STL Vector Memory Contiguous After Resizing?. For more information, please follow other related articles on the PHP Chinese website!