Accessing raw values in a vector

B

Bob Altman

Hi all,

In unmanaged C++, I need to allocate an "array" of int values, put values
into the array, then call a function and pass it the address and length of
the array. The length of the array is only known at run-time, so I assume
that my best course of action is to use a std::vector object for the
"array". My question is, am I guaranteed that the vector stores its data in
contiguous memory, so that I can use vector.begin() as a pointer to the
memory containing my contiguous array of data?
 
C

Carl Daniel [VC++ MVP]

Bob Altman said:
Hi all,

In unmanaged C++, I need to allocate an "array" of int values, put values
into the array, then call a function and pass it the address and length of
the array. The length of the array is only known at run-time, so I assume
that my best course of action is to use a std::vector object for the
"array". My question is, am I guaranteed that the vector stores its data
in
contiguous memory, so that I can use vector.begin() as a pointer to the
memory containing my contiguous array of data?

Yes, you are.

-cd
 
A

Arnaud Debaene

Bob said:
My question is, am I guaranteed
that the vector stores its data in contiguous memory,
Practically speaking yes (although it is not yet in the norm, it will soon
be).
so that I can
use vector.begin() as a pointer to the memory containing my
contiguous array of data?
That, on the other hand, is wrong : there is no guarantee than a vector
iterator can be used as a pointer : You can use &MyVect[0] to get a pointer
to the begnning of the vector buffer.

Arnaud
MVP - VC
 
T

Tom Widmer

Arnaud said:
Practically speaking yes (although it is not yet in the norm, it will soon
be).

The 2003 standard says it explicitly: "The elements of a vector are
stored contiguously, meaning that if v is a vector<T, Allocator> where T
is some type other than bool, then it obeys the identity &v[n] == &v[0]
+ n for all 0 <= n < v.size()."

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top