Home  >  Q&A  >  body text

hashmap - c++ hash_map 持久化

c++ 中怎么将hash_map 存储到文件中 这个牵扯到序列化和反序列化 有做过这方面的大神吗?据说boost 库提供了一个 方法 但是查到的资料很少。有谁有这方面的资料 共享下 谢谢!!!

高洛峰高洛峰2765 days ago668

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 12:01:51

    As long as hash_map can be traversed, it can be serialized. Generally, collection data structures can be traversed, and hash_map is no exception

    Serialization

    Get the number of items through the size() method of the hash_map object and write it to the stream,
    Traverse the hash_map object through hash_map::iterator and write the key and value to the stream in turn.

    Deserialization

    A hash_map object is generated when reading,
    First read the quantity, and then perform a for loop based on this quantity,
    Read the key and value pairs in sequence and insert them into the hash_map object just now

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 12:01:51

    If you consider a third-party library, Google’s protobuf is recommended, which can directly serialize the hash_map object and store it;

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 12:01:51

    I don’t know the size of your data and the modification frequency of hash_map. Let me just talk about my current situation and implementation
    My map has about a few thousand to tens of thousands items. Additions, deletions and modifications are infrequent, and persistence is done in shared memory.
    Therefore, the shared memory structure defines a struct, which contains key and value. When the program is running, all additions, deletions, and modifications to the map are converted into writes to the shared memory. When the program restarts, all items are read from the shared memory and the map is re-formed.

    reply
    0
  • Cancelreply