boost::serialization 仅序列化映射的键
我有一个带有地图的类,我想使用 boost 序列化来序列化该类。
std::map<int, ComplicatedThing> stuff;
只需知道 int 即可推导出 ComplicatedThing。我想有效地序列化它。一种方法(虽然很糟糕,但可行)是创建键向量并序列化该向量。
// 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;
}
但这是不优雅的。使用 BOOST_SERIALIZATION_SPLIT_MEMBER() 和加载/保存方法,我想我应该能够完全跳过中间向量的分配。我被困住了。
也许我的答案在于理解 boost/serialization/collections_load_imp.hpp。希望有一条更简单的路径。
I have a class with a map, and I want to serialize the class using boost serialize.
std::map<int, ComplicatedThing> 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将其序列化为
int
列表(我不是指std::list
),而不是将其序列化为容器(地图或矢量)。首先写出元素的数量,然后将它们一一写出,相应地反序列化。这是10分钟的任务。如果您在很多地方都需要此解决方案,请将映射包装在您的类中并为其定义序列化you can serialize it as list of
int
s (I don't meanstd::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如果你想让它看起来不笨拙,请使用 范围适配器
或者,如果您包含适当的标头,我想您可以将其减少为
免责声明
serialize
设置中效果不佳(您需要阅读 http://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/serialization.html#splitting)If you want to make it not look clumsy, use range adaptors
Or if you include the appropriate headers, I suppose you could reduce this to
Disclaimer
serialize
setting (you'll want to read http://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/serialization.html#splitting)