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
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With