gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:33:12 27 4
gpt4 key购买 nike

有没有一种简单的方法来使用自定义分配器(或者,更好的是,通过配置标准分配器)和 C++ 中的无序 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com