How do I serialize and deserialize std::pair in C++?

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;
}
    

serialization deserialization std::pair C++ C++ examples C++ tutorial