In C , the STL vector provides a dynamic array that automatically resizes as elements are added or removed. However, one common question arises: is it safe to assume that the vector's elements are always stored contiguously in memory?
To address this concern, consider the following scenario:
vector<char> vc(100); // Perform operations on vc vc.resize(200); char* p = &vc[0]; // Conduct operations using *p
The question is, can we reliably access the rest of the vector's elements sequentially in memory using the address of the first element (*p) after resizing the vector?
Answer: Yes, that assumption is valid.
According to the C 03 standard (23.2.4.1), contiguous storage is guaranteed for vectors:
"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 implies that the memory addresses of subsequent elements in the vector can be calculated by incrementing the address of the first element by the size of the element type. In other words, the elements are stored in a linear fashion.
Important Note:
While contiguous storage is guaranteed, it's crucial to remember that the vector may need to be reallocated during addition operations, which could invalidate any pointers and iterators. Therefore, it's essential to consider this possibility when working with pointers to vector elements.
The above is the detailed content of Are STL Vectors Guaranteed to Store Elements Contiguously in Memory?. For more information, please follow other related articles on the PHP Chinese website!