In C++, to serialize and deserialize an std::unordered_map
, we can use various techniques, including JSON or binary serialization. For large datasets, it is crucial to ensure that the serialization process is efficient to minimize memory usage and processing time.
Serialization involves transforming the std::unordered_map
into a storable format. For an unordered map, we typically convert each key-value pair into a string format. Here’s an example using JSON format for serialization:
#include <unordered_map>
#include <string>
#include <fstream>
#include <nlohmann/json.hpp> // for JSON handling
using json = nlohmann::json;
std::string serialize(const std::unordered_map<std::string, int> &data) {
json j = data; // convert to JSON
return j.dump(); // return JSON as string
}
Deserialization is the reverse process where we convert the stored format back into an std::unordered_map
. Here's how we can do it:
std::unordered_map<std::string, int> deserialize(const std::string &str) {
json j = json::parse(str); // parse JSON string
return j.get<std::unordered_map<std::string, int>>(); // convert to unordered_map
}
int main() {
std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};
// Serialize
std::string serializedData = serialize(myMap);
// Save to file
std::ofstream outFile("data.json");
outFile << serializedData;
outFile.close();
// Load from file
std::ifstream inFile("data.json");
std::string deserializedData((std::istreambuf_iterator<char>(inFile)), std::istreambuf_iterator<char>());
// Deserialize
auto newMap = deserialize(deserializedData);
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?