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
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.
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
If you consider a third-party library, Google’s protobuf is recommended, which can directly serialize the hash_map object and store it;
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.