Getting address of buffer of vector.

F

Fred Zwarts

For some operations, e.g., if one needs to write a large vector of floats to a file,
the address of a buffer is needed.
Does the vector class is the STL offer a way to get access to its internal buffer?
Is &V[0] the answer?
I'm afraid it is not, because I understand that the structure of the internal
buffer is hidden and may be implementation specific. Maybe it is not even
contiguous.
So, what is the most efficient way to code this in a portable way?
Should I write the elements of the vector one by one, or should I first
copy the elements to a dedicated array of floats and than write the whole
array? I think the first solution has more overhead, whereas the second
solution may cost a lot of extra memory and looses the advantages of
vectors compared to arrays.

Of course the same questions can be asked for other (elementary) types,
other containers and other operations, so, I appreciate generic answers.

F.Z.
 
J

Johann Gerell

All of

&V[0] and &V.front() and &V.at(0)

are guaranteed to give you a pointer to the vector's contiguous memory.
 
B

bart.kowalski

Johann said:
All of

&V[0] and &V.front() and &V.at(0)

are guaranteed to give you a pointer to the vector's contiguous memory.

But also note that other containers don't necessarily give such a
guarantee.
 
M

msalters

(e-mail address removed) schreef:
Johann said:
All of

&V[0] and &V.front() and &V.at(0)

are guaranteed to give you a pointer to the vector's contiguous memory.

But also note that other containers don't necessarily give such a
guarantee.

In fact, only std::string could (but doesn't). All other containers
must be implemented with multiple buffers to achieve their big-O
requirements.
For std::string, you can of course use .data() to get a (copy of)
the buffer. Read-only, of course.

HTH,
Michiel Salters
 

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

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top