Home > Backend Development > C++ > body text

Is STL Vector Memory Contiguous After Resizing?

Susan Sarandon
Release: 2024-11-18 04:47:02
Original
689 people have browsed it

Is STL Vector Memory Contiguous After Resizing?

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, is it safe to assume that the address of the first element (&vc[0]) represents the starting point of a contiguous block of memory occupied by the entire vector?

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template