Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy binary data to a stringstream

Tags:

c++

stl

I have a std::vector<int> and I want serialize it. For this purpose I am trying to use a std::stringstream

 vector<int> v;
 v.resize(10);
 for (int i=0;i<10;i++)
 v[i]=i;


 stringstream ss (stringstream::in | stringstream::out |stringstream::binary);

However when I copy the vector to the stringstream this copy it as character

ostream_iterator<int> it(ss);
copy(v.begin(),v.end(),it);

the value that inserted to buffer(_Strbuf) is "123456789"

I sucssesed to write a workaround solution

for (int i=1;i<10;i++)
   ss.write((char*)&p[i],sizeof(int));

I want to do it something like first way by using std function like copy

thanks Herzl

like image 552
herzl shemuelian Avatar asked Feb 01 '11 14:02

herzl shemuelian


2 Answers

Actually, this is your workaround but it may be used with std::copy() algorithm.

   template<class T>
   struct serialize
   {
      serialize(const T & i_value) : value(i_value) {}
      T value;
   };

   template<class T>
   ostream& operator <<(ostream &os, const serialize<T> & obj)
   {
      os.write((char*)&obj.value,sizeof(T));
      return os;
   }

Usage

ostream_iterator<serialize<int> > it(ss);
copy(v.begin(),v.end(),it);
like image 131
Stas Avatar answered Sep 21 '22 09:09

Stas


I know this is not an answer to your problem, but if you are not limited to the STL you could try (boost serialization) or google protocol buffers

Boost even has build-in support for de-/serializing STL containers (http://www.boost.org/doc/libs/1_45_0/libs/serialization/doc/tutorial.html#stl)

like image 33
Martin Avatar answered Sep 22 '22 09:09

Martin