Accessing raw values in a vector

  • Thread starter Thread starter Bob Altman
  • Start date Start date
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?
 
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
 
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
 
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
 
Back
Top