Is it possible to assume that the STL vector storage is always contiguous?

If you have an STL vector that has been changed, is it safe to take the address of element 0 and assume that the rest of the vector will follow in memory?

eg.

vector<char> vc(100); // do some stuff with vc vc.resize(200); char* p = &vc[0]; // do stuff with *p 
+54
c ++ vector stl
Oct 29 '08 at 17:44
source share
6 answers

Yes, this is a valid assumption (*).

From the C ++ 03 standard (23.2.4.1):

Elements of the vector are stored adjacent, which means that if v is a vector, where T is some type other than bool, then it obeys the identifier & v [n] == & v [0] + n for all 0 <= n <V .SIZE ().

(*) ... but make sure that the array is redistributed (invalidating any pointers and iterators) after adding elements to it.

+71
Oct 29 '08 at 17:50
source share
— -

The standard wording added by C ++ 03 is to make it clear that vector elements must be contiguous.

C ++ 03 23.2.4 Paragraph 1 contains the following language, which is not found in the standard C ++ 98 document:

The elements of a vector are stored adjacent, which means that if v is vector<T, Allocator> where T some type other than bool , then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size() .

Herb Sutter talks about this change in one of his blog entries, Cringe not: Vectors are guaranteed to be contiguous :

... Adjacency is actually part of a vector abstraction. Its so important, in fact, when it was discovered that the C ++ 98 standard didnt fully guarantee contact, the C ++ 03 standard was amended explicitly to add a guarantee.

+27
Oct 29 '08 at 18:34
source share

Storage is always contiguous, but it can move as the vector capacity changes.

If you had a pointer, link, or iterator on a null element (or any element) before the capacity change operation, it is invalid and must be reassigned.

+13
Oct 29 '08 at 17:49
source share
+10
Oct 29 '08 at 17:47
source share

std::vector ensures that elements are stored in a continuous array and, therefore, are the preferred replacement for arrays, and can also be used to interact with platform-specific low-level code (for example, calls to the Win32 API). To get a pointer to an array, use:

 &myVector.front(); 
+4
Oct 29 '08 at 17:50
source share

Yes.

it must always be adjacent

+2
Oct 29 '08 at 17:46
source share



All Articles