I have various structures ( comprised of integral types and arrays of integral types ) and an array of unsigned chars that I want to add to a vector of unsigned chars.
So, given the following pseudocode:
struct
{
short x;
short sz;
unsigned char y;
unsigned char w;
unsigned char z[ 2 ];
} example_struct;
example_struct ex_s;
unsigned char array[ <some val-could be several thousand> ];
I looked at this question: Convert a struct to vector of bytes and I wrote the following:
std::vector< unsigned char > v( sizeof( example_struct ) + array_len );
unsigned char * ptr = reinterpret_cast< unsigned char * >( &ex_s );
std::vector< unsigned char > tmp_v( ptr, ptr + sizeof( example_struct ) );
v = tmp_v;
std::vector< unsigned char > tmp_v2( array, array + array_len );
v.insert( v.end(), tmp_v2.begin(), tmp_v2.end() );
Is there an easier ( more readable ) way to do it?
Would it be more efficient to create v with the contents of the structure rather than assigning the temporary variable to it?
If that is done, then v wouldn't be the size of the final length most likely resulting in another memory allocation via the vector when the array is added. Would an empty vector creation followed by a reserve of the total length plus the additions be preferred?
Is swap preferred over assignment?
Is insert the preferred way to add the 2nd vector?
Any other recommendation on how you'd write this?