Home >Backend Development >C++ >Do STL Vector Elements Remain Consecutive in Memory After Resizing?

Do STL Vector Elements Remain Consecutive in Memory After Resizing?

Susan Sarandon
Susan SarandonOriginal
2024-11-16 07:26:03581browse

Do STL Vector Elements Remain Consecutive in Memory After Resizing?

Storage Contiguity of STL Vector Elements

When working with STL vectors, it's essential to understand the memory layout of their elements. A common question arises: if a vector has been resized, can we safely assume that its elements are stored contiguously in memory?

Analysis

The C 03 standard (23.2.4.1) provides the answer:

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 &amp;v[n] == &amp;v[0] + n for all 0 <= n < v.size().

In simpler terms, this means that the address of the first element (&v[0]) of a vector is equal to the address of its n-th element (&v[n]) plus the offset of n. This applies to vectors containing data types other than booleans.

Example

Consider the following code:

vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p

According to the standard, we can safely assume that after resizing the vector, the address stored in p will provide contiguous access to all 200 elements of the vector. This is because the elements of the vector are guaranteed to be stored one after the other in memory, allowing for efficient traversal and access.

Caution

However, it's important to note that when adding elements to a vector, its storage may be reallocated. This can invalidate any existing pointers or iterators to the vector elements, so it's essential to take this into account when working with vectors.

The above is the detailed content of Do STL Vector Elements Remain Consecutive in Memory After Resizing?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn