STL: Use vector to wrap existing array?

Started by
2 comments, last by panic1227 18 years, 3 months ago
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 );
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.
:stylin: "Make games, not war.""...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid
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.
i think

write a special allocator for this vector,
or
write a specialization of vector

This topic is closed to new replies.

Advertisement