How do I serialize a vector of deques using Boost Serialization library.
Currently, I have the following code for this purpose:
#include <boost/serialization/deque.hpp> //in includes
Item1(6128, std::deque<float> ()), //constructor initializations
Item2(6128, std::deque<float> ()),
Item3(6128,std::deque<开发者_如何学编程;int> ()),
Item4(6128,std::deque<int> ()),
private:
friend class boost::serialization::access;
template <typename Archive>
void
serialize(Archive &ar,
const unsigned int /*file_version*/)
{
for (unsigned i = 0; i < Item1.size(); ++i)
{ar & Item1[i];}
for (unsigned i = 0; i < Item2.size(); ++i)
{ar & Item2[i];}
for (unsigned i = 0; i < Item3.size(); ++i)
{ar & Item3[i];}
for (unsigned i = 0; i < Item4.size(); ++i)
{ar & Item4[i];}
}
std::vector< std::deque<float> > Item1, Item2;
std::vector< std::deque<int> > Item3, Item4;
This code compiles and runs fine. However, the values I store are different from the ones I loaded while serializing. Am I doing something wrong? Is this the right method to serialize a vector of deques?
Your feedback is appreciated. Thanks!
You are not serializing the size of Item1...Item4
I suggest you use STL container serialization directly:
- http://www.boost.org/doc/libs/1_47_0/libs/serialization/doc/tutorial.html#stl
- http://www.boost.org/doc/libs/1_47_0/libs/serialization/doc/serialization.html#models
e.g.
ar & Item1;
ar & Item2;
ar & Item3;
ar & Item4;
Alternatively you could split into Load/Save methods and save / load the container size explicitely.
template<class Archive>
void save(Archive & ar, const unsigned int version) const
{
ar & Item1.size();
for (unsigned i = 0; i < Item1.size(); ++i)
{ar & Item1[i];}
ar & Item2.size();
for (unsigned i = 0; i < Item2.size(); ++i)
{ar & Item2[i];}
// etc...
}
template<class Archive>
void load(Archive & ar, const unsigned int version)
{
size_t size;
ar & size;
Item1.resize(size);
for (unsigned i = 0; i < Item1.size(); ++i)
{ar & Item1[i];}
ar & size;
Item2.resize(size);
for (unsigned i = 0; i < Item2.size(); ++i)
{ar & Item2[i];}
// etc...
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
精彩评论