boost::serialization 仅序列化映射的键

发布于 2024-11-18 18:48:05 字数 780 浏览 2 评论 0原文

我有一个带有地图的类,我想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

画中仙 2024-11-25 18:48:05

您可以将其序列化为 int 列表(我不是指 std::list),而不是将其序列化为容器(地图或矢量)。首先写出元素的数量,然后将它们一一写出,相应地反序列化。这是10分钟的任务。如果您在很多地方都需要此解决方案,请将映射包装在您的类中并为其定义序列化

you can serialize it as list of ints (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

唯憾梦倾城 2024-11-25 18:48:05

如果你想让它看起来不笨拙,请使用 范围适配器

 ar & (stuff | transformed(boost::bind(&map_type::value_type::first, _1));

或者,如果您包含适当的标头,我想您可以将其减少为

 ar & (stuff | transformed(&map_type::value_type::first))

免责声明

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文