I have a class with a map, and I want to serialize the class using boost serialize.
std::map<int, Compli开发者_JS百科catedThing> stuff;
ComplicatedThing is derivable just by knowing the int. I want to serialize this efficiently. One way (ick, but works) is to make a vector of the keys and serialize the vector.
// illustrative, not test-compiled
std::vector<int> v;
std::copy(stuff.begin, stuff.end, std::back_inserter(v));
// or
for(std::vector<int> it = v.begin(); it != v.end(); it++)
stuff[*it] = ComplicatedThing(*it);
// ...and later, at serialize/deserialize time
template<class Archive>
void srd::leaf::serialize(Archive &ar, const unsigned int version)
{
ar & v;
}
But this is inelegant. Using BOOST_SERIALIZATION_SPLIT_MEMBER() and load/save methods, I think I should be able to skip the allocation of the intermediate vector completely. And there I am stuck.
Perhaps my answer lies in understanding boost/serialization/collections_load_imp.hpp. Hopefully there is a simpler path.
you can serialize it as list of int
s (I don't mean std::list
) instead of serializing it as a container (map or vector). fist write number of elements and then them one by one, deserizalize accordingly. it's 10 mins task. if you need this solution in many places, wrap map in your class and define serialization for it
If you want to make it not look clumsy, use range adaptors
ar & (stuff | transformed(boost::bind(&map_type::value_type::first, _1));
Or if you include the appropriate headers, I suppose you could reduce this to
ar & (stuff | transformed(&map_type::value_type::first))
Disclaimer
- All of this assumes that Boost Serialization ships with serializers for Boost Ranges (haven't checked)
- This might not work well in a bidirectional
serialize
setting (you'll want to read http://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/serialization.html#splitting) - I haven't brought the above into the vicinity of a compiler
精彩评论