c++ - 使用分配器对 HashMap 进行高效序列化和反序列化

标签 c++ serialization deserialization allocation c++-standard-library

是否有一种简单的方法可以在 C++ 中使用带有无序 HashMap 或多映射的自定义分配器(或者更好的是,通过配置标准分配器),以便键、值和存储桶结构始终保存在连续内存中以相对紧凑的形式?

如果是这样,这样的分配器是否可以用于保存和恢复映射,而无需迭代键然后通过插入进行恢复的显式序列化要求?

如果没有,是否有另一种方法可以序列化和反序列化 HashMap ,而无需在反序列化期间重新哈希每个键?

最佳答案

Is there a simple way to use a custom allocator

是的

(or, better yet, by configuring a standard allocator)

没有

with an unordered hash map or multimap in C++ so that the keys, values, and bucket structure are always kept in contiguous memory in a relatively packed form?

是的

If so, can such an allocator then be used to save and restore the map without the explicit serialization requirement of iterating through the keys and then restoring by inserting?

不,因为在程序的两次运行之间,标准规定您不能假设哈希值相同。

但是你的问题有一个错误的前提。这不是序列化 unordered_map 的方法。

If not, is there another way to serialize and deserialize a hash map that does not necessitate rehashing each key during deserialization?

是 - 用于序列化:

serialise_length(archive, map.size());
for (auto const& element : map)
{
    auto const& key = element.first;
    auto const& value = element.second;
    serialise_nvp(archive, key, value);
}

当然,您将提供 serialise_length()serialise_nvp() 函数以及 archive 对象。

对于反序列化:

auto map = std::unordered_map<Key, Value>();
auto length = deserialise_length(archive);
map.reserve(length);
while (length--)
{
    auto key = deserialise<Key>(archive);
    auto value = deserialise<Value>(archive);
    map.emplace(std::move(key), std::move(value));
}

auto map = std::unordered_map<Key, Value>();
auto length = deserialise_length(archive, length);
map.reserve(length);
while (length--)
{
    auto kv = deserialise_nvp<Key, Value>(archive);
    map.insert(std::move(kv));
}

关于c++ - 使用分配器对 HashMap 进行高效序列化和反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41833856/

相关文章:

c# - 从 C++ 升级到 C#

c# - 从字符串反序列化时使用 XmlSerializer.CanDeserialize()

java - 不可变业务对象和 MessagePack 消息之间的自动转换

c# - C#中XML文件的反序列​​化

c++ - boost::lockfree::queue 正在耗尽我的 CPU

C++ 11 异步和 future 输出无序

c++ - 将 C++ 模块连接到 QML - ReferenceError : <blank> is not defined

json - 使用 Redis 进行 Spring Boot 缓存 - 反序列化问题

Java反序列化实例变量发生变化

c# - 使用 Json.NET 的 Json 反序列化中的 JsonSerializationException