STL: Use vector to wrap existing array?

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

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 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 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 on other sites
i think

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

• 10
• 17
• 9
• 13
• 41