Sign in to follow this  

STL: Use vector to wrap existing array?

This topic is 4353 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

A system call (to retrieve console input events) allocates an array, assigns it to an out parameter, and returns the size of the array. I want to wrap up the data in an STL vector. Is there a way to assign an STL vector a buffer rather than copying the array contents into a new vector and deleting the original array? ~BenDilts( void );

Share this post


Link to post
Share on other sites
You want to construct your vector with this,

template<class InputIterator>
vector(
InputIterator _First,
InputIterator _Last
);

but I don't see a way around deleting the old array.

Share this post


Link to post
Share on other sites
Not terribly sanely. I'd recommend using the vector to allocate the array as well. Then you get:

//old equiv: size_t example( char ** out ) or ( char *& out )
size_t example( std::vector< char > & out ) {
out.resize( 25 ); //instead of: out = (char *)malloc( 25 ); or similarly ugly non-RAII solution
//if you need to fill out using a C-style function:
cee_style_function( &(out[0]) );

//and we can of course use STL algorithms:
std::fill( out.begin() , out.end() , ' ' );

return out.size();
}



If you really intend to work with pre-existing memory allocated by something else, std::vector is likely unsuitable. The Boost Smart Pointers Library's boost::scoped_array or boost::shared_array may be useful, if your main concern is RAII wrapping.

Share this post


Link to post
Share on other sites

This topic is 4353 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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