Mark Miles
Mark Miles

Reputation: 706

Copy struct to 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?

Upvotes: 4

Views: 6722

Answers (1)

Columbo
Columbo

Reputation: 61009

You can try the iterator-pair constructor:

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

std::vector<unsigned char> myVector( ptr, ptr + sizeof myStructure );

Upvotes: 9

Related Questions