The underlying implementation of a vector is
always** guaranteed to be a contiguous block of memory, no matter what you do to it. If you declare your vector as std::vector<unsigned char> and treat it as a byte array, then the type/size of the data you actually store in it (whether its a struct, int, etc) will be irrelevant so long as it actually fits within the size you've allocated.
You can do a reinterpret_cast to overlay any kind of pointer interface of your choosing, and this will ensure that copying in/out of the byte buffer works for that particular type.
e.g.
1 2 3 4 5 6 7 8 9
|
static const size_t howmany = sizeof(int) * 10;
// define its size and fill it up with lots of zero bytes
std::vector<unsigned char> bytes( howmany, '\0' );
int* begin = reinterpret_cast<int*>( &bytes[0] );
int* end = reinterpret_cast<int*>( &bytes[0] + howmany );
std::vector<int> numbers( begin, end );
|
in this particular case I wouldn't suggest using 'reserve', because you almost certainly want your vector::size() to return the number of bytes that you're actually using. Specifying the size as part of the constructor call, or using resize would be most appropriate IMO.
** "always" - unless you do something "weird" like define your own replacement for std::allocator or overload the
new operator, then you could stop it from being stored contiguously - but if you were doing that, then you'd probably not be here asking that question :)