Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy struct to vector

Tags:

c++

struct

vector

Say I have a structure of various data types, I want to copy each single byte in a vector. I do this:

vector<unsigned char> myVector;                                     // get a vector
unsigned char buf[sizeof myStructure];                              // get an array
memcpy(&buf, &myStructure, sizeof myStructure);                     // copy struct to array
myVector.insert(myVector.begin(), buf, buf + sizeof myStructure);   // copy array to vector

Is there a quickest way that allows me to copy the struct myStruct to vector myVector without passing through the array buf?

like image 272
Mark Miles Avatar asked Mar 20 '23 11:03

Mark Miles


1 Answers

You can try the iterator-pair constructor:

auto const ptr = reinterpret_cast<unsigned char*>(&myStructure);

std::vector<unsigned char> myVector( ptr, ptr + sizeof myStructure );
like image 195
Columbo Avatar answered Mar 31 '23 05:03

Columbo