Search code examples
c++castinggeneric-programming

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 casting 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());
}

Solution

  • 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).