Sign in to follow this  
john_t

STL array?

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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) ...

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this