Jump to content
  • Advertisement
Sign in to follow this  
BeanDog

STL: Use vector to wrap existing array?

This topic is 4604 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!