C++動態二維數組可以序列化,但需要自定義序列化和反序列化的過程。一種常見的方法是將二維數組轉換為一維數組,然后序列化一維數組。在反序列化時,再將一維數組還原為二維數組。
下面是一個示例代碼,用于序列化和反序列化動態二維數組:
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
// 序列化二維數組
std::string serialize(std::vector<std::vector<int>>& arr) {
std::stringstream ss;
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr[i].size(); j++) {
ss << arr[i][j] << " ";
}
ss << "\n";
}
return ss.str();
}
// 反序列化二維數組
std::vector<std::vector<int>> deserialize(std::string data) {
std::vector<std::vector<int>> arr;
std::stringstream ss(data);
std::string line;
while (std::getline(ss, line)) {
std::vector<int> row;
std::stringstream row_ss(line);
int num;
while (row_ss >> num) {
row.push_back(num);
}
arr.push_back(row);
}
return arr;
}
int main() {
// 創建動態二維數組
std::vector<std::vector<int>> arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// 序列化并輸出
std::string serialized_data = serialize(arr);
std::cout << "Serialized data: " << serialized_data << std::endl;
// 反序列化并輸出
std::vector<std::vector<int>> deserialized_arr = deserialize(serialized_data);
std::cout << "Deserialized data: " << std::endl;
for (int i = 0; i < deserialized_arr.size(); i++) {
for (int j = 0; j < deserialized_arr[i].size(); j++) {
std::cout << deserialized_arr[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
這段代碼中,serialize函數將二維數組轉換為字符串,deserialize函數將字符串還原為二維數組。通過這種方法,動態二維數組可以被序列化和反序列化。