Store data of different types into a vector<char>?
I'm trying to write a generic function that casts and stores arguments of different data types into a vector<char>
. By cast开发者_运维百科ing I mean that the bit representation is preserved within the vector of characters. For instance a 4 byte int
such as 0x19a4f607
will be stored in the vector as vc[0] = 0x19
, vc[1] = 0xa4
, vc[2] = 0xf6
and vc[3] = 0x07
.
Here is what I have written so far, but I get a segmentation fault. Any idea how I can fix this?
template <class T>
void push_T(vector<char>& vc, T n){
char* cp = (char*)&n;
copy(cp, cp+sizeof(T), vc.end());
}
You need an iterator that is capable of inserting at the end of the vector; .begin()
and .end()
are only capable of modifying existing elements. Try std::back_inserter(vc)
.
The immediate problem here is that you haven't made any effort to resize your vector, so you immediately write off the end of the underlying array. You need to precede the copy()
call with a vc.resize(vc.size() + sizeof(T))
, or use a std::back_inserter
insert iterator to force push_back() behavior on the copy.
Now, I'll assume you have a good reason for subverting the type system in the first place....
精彩评论