您好,登錄后才能下訂單哦!
在C++中,序列化是將對象的狀態(tài)信息轉(zhuǎn)換為可以存儲或傳輸?shù)母袷降倪^程
示例代碼:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <fstream>
#include <vector>
int main() {
// 保存數(shù)據(jù)到文件
std::ofstream ofs("data.txt");
boost::archive::text_oarchive oa(ofs);
std::vector<int> data = {1, 2, 3, 4, 5};
oa << data;
// 從文件加載數(shù)據(jù)
std::ifstream ifs("data.txt");
boost::archive::text_iarchive ia(ifs);
std::vector<int> loaded_data;
ia >> loaded_data;
}
示例代碼:
#include <cereal/archives/binary.hpp>
#include <cereal/types/vector.hpp>
#include <fstream>
#include <vector>
int main() {
// 保存數(shù)據(jù)到文件
std::ofstream ofs("data.bin", std::ios::binary);
cereal::BinaryOutputArchive oa(ofs);
std::vector<int> data = {1, 2, 3, 4, 5};
oa(data);
// 從文件加載數(shù)據(jù)
std::ifstream ifs("data.bin", std::ios::binary);
cereal::BinaryInputArchive ia(ifs);
std::vector<int> loaded_data;
ia(loaded_data);
}
#include <iostream>
#include <fstream>
#include <stdexcept>
void save_data(const std::string& filename) {
try {
std::ofstream ofs(filename, std::ios::binary);
if (!ofs) {
throw std::runtime_error("無法打開文件");
}
// 執(zhí)行序列化操作
} catch (const std::exception& e) {
std::cerr << "保存數(shù)據(jù)時發(fā)生錯誤: " << e.what() << std::endl;
}
}
void load_data(const std::string& filename) {
try {
std::ifstream ifs(filename, std::ios::binary);
if (!ifs) {
throw std::runtime_error("無法打開文件");
}
// 執(zhí)行反序列化操作
} catch (const std::exception& e) {
std::cerr << "加載數(shù)據(jù)時發(fā)生錯誤: " << e.what() << std::endl;
}
}
int main() {
save_data("data.bin");
load_data("data.bin");
}
在這個示例中,我們使用了C++的異常處理機(jī)制來捕獲和記錄序列化過程中可能出現(xiàn)的錯誤。當(dāng)發(fā)生錯誤時,我們將錯誤信息輸出到標(biāo)準(zhǔn)錯誤流(std::cerr)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。