Serialization and deserialization are important techniques in C++ for converting complex data types into a format that can be easily stored or transmitted and then reconstructed later. Here's how to serialize and deserialize `std::pair` in C++.
serialization, deserialization, std::pair, C++, C++ examples, C++ tutorial
This article explains how to use serialization and deserialization techniques on std::pair in C++, making it easy to save and restore data structures.
#include <iostream>
#include <utility> // for std::pair
#include <sstream> // for std::stringstream
// Function to serialize std::pair
template <typename T1, typename T2>
std::string serialize(const std::pair<T1, T2> &p) {
std::ostringstream oss;
oss << p.first << "," << p.second;
return oss.str();
}
// Function to deserialize std::pair
template <typename T1, typename T2>
std::pair<T1, T2> deserialize(const std::string &data) {
std::istringstream iss(data);
T1 first;
T2 second;
char comma; // to consume the comma
iss >> first >> comma >> second;
return std::make_pair(first, second);
}
int main() {
std::pair<int, std::string> originalPair = std::make_pair(42, "Hello");
// Serialize the pair
std::string serialized = serialize(originalPair);
std::cout << "Serialized: " << serialized << std::endl;
// Deserialize the pair
auto deserializedPair = deserialize<int, std::string>(serialized);
std::cout << "Deserialized: (" << deserializedPair.first << ", " << deserializedPair.second << ")" << std::endl;
return 0;
}
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?