STL array?

Started by
3 comments, last by GameDev.net 18 years, 1 month ago
I can't seem to find an STL container that will supply me with a pointer to an array of its contents. I would think that the obvious candidate would be vector, but it doesn't expose this functionality. It seems that such function should exist--for instance, string will supply a char* to its data with string::c_str(). Am I missing something obvious?
Advertisement
I would have to read the spec a lot closer, but I believe vector.begin() can be used this way ... although I'm not sure how strict this is ... I know the rule says a vector must contain a contiguous block of memory for its items (ignore vector<bool> for the love of god) ...
I think this will work.
std::vector<int> myvector;
int *p = &myvector[0];

I'd recommend against doing this though, unless you just have to pass in a * to some legacy function you can't change.
Thanks.

Quote:
unless you just have to pass in a * to some legacy function you can't change


Thats exactly what I'm doing :)

I assume I can just pass in vector::size() as the size of the array then as well. It's good to know that vector is required to keep its memory contiguous--this should work then.
Quote:Original post by Anonymous Poster
Thats exactly what I'm doing :)

I assume I can just pass in vector::size() as the size of the array then as well. It's good to know that vector is required to keep its memory contiguous--this should work then.


It's not required to be contiguous in the old C++ standard, but due to the other requirements on vectors you'd be hard pressed to find an implementation where it wasn't. The new C++ standard explicitly states that a vector must be contiguous.

This topic is closed to new replies.

Advertisement