[英]boost::serialization to serialize only the keys of a map
I have a class with a map, and I want to serialize the class using boost serialize.我有一个 class 和一个 map,我想使用 boost 序列化序列化 class。
std::map<int, ComplicatedThing> stuff;
ComplicatedThing is derivable just by knowing the int.仅通过知道 int 就可以推导出 ComplicatedThing。 I want to serialize this efficiently.我想有效地序列化它。 One way (ick, but works) is to make a vector of the keys and serialize the vector.一种方法(ick,但有效)是制作一个键向量并序列化该向量。
// 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.使用 BOOST_SERIALIZATION_SPLIT_MEMBER() 和加载/保存方法,我想我应该能够完全跳过中间向量的分配。 And there I am stuck.我被困住了。
Perhaps my answer lies in understanding boost/serialization/collections_load_imp.hpp.也许我的答案在于理解 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).您可以将其序列化为int
的列表(我不是指std::list
),而不是将其序列化为容器(地图或矢量)。 fist write number of elements and then them one by one, deserizalize accordingly.首先写入元素的数量,然后一个一个地写入,相应地反序列化。 it's 10 mins task.这是 10 分钟的任务。 if you need this solution in many places, wrap map in your class and define serialization for it如果您在很多地方都需要此解决方案,请将 map 包装在您的 class 中并为其定义序列化
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免责声明
serialize
setting (you'll want to read http://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/serialization.html#splitting )这在双向serialize
设置中可能效果不佳(您需要阅读http://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/serialization.html#splitting )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.