[英]Boost binary serialization with a map and doubles crashes on serialize in
[英]boost::serialization to serialize only the keys of a map
我有一個 class 和一個 map,我想使用 boost 序列化序列化 class。
std::map<int, ComplicatedThing> stuff;
僅通過知道 int 就可以推導出 ComplicatedThing。 我想有效地序列化它。 一種方法(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;
}
但這是不雅的。 使用 BOOST_SERIALIZATION_SPLIT_MEMBER() 和加載/保存方法,我想我應該能夠完全跳過中間向量的分配。 我被困住了。
也許我的答案在於理解 boost/serialization/collections_load_imp.hpp。 希望有更簡單的路徑。
您可以將其序列化為int
的列表(我不是指std::list
),而不是將其序列化為容器(地圖或矢量)。 首先寫入元素的數量,然后一個一個地寫入,相應地反序列化。 這是 10 分鍾的任務。 如果您在很多地方都需要此解決方案,請將 map 包裝在您的 class 中並為其定義序列化
如果您想讓它看起來不笨拙,請使用范圍適配器
ar & (stuff | transformed(boost::bind(&map_type::value_type::first, _1));
或者,如果您包含適當的標題,我想您可以將其減少到
ar & (stuff | transformed(&map_type::value_type::first))
免責聲明
serialize
設置中可能效果不佳(您需要閱讀http://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/serialization.html#splitting )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.