在Ubuntu中,C++实现序列化可以使用多种方法。以下是一些常用的序列化库和方法:
Boost.Serialization是一个非常强大的库,可以序列化几乎所有的C++数据类型。
sudo apt-get update
sudo apt-get install libboost-all-dev
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <iostream>
#include <fstream>
#include <vector>
class Person {
public:
std::string name;
int age;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & name;
ar & age;
}
};
int main() {
std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}};
// 序列化到文件
{
std::ofstream ofs("people.txt");
boost::archive::text_oarchive oa(ofs);
oa << people;
}
// 从文件反序列化
std::vector<Person> loaded_people;
{
std::ifstream ifs("people.txt");
boost::archive::text_iarchive ia(ifs);
ia >> loaded_people;
}
// 打印反序列化后的数据
for (const auto& person : loaded_people) {
std::cout << person.name << " " << person.age << std::endl;
}
return 0;
}
Cereal是一个轻量级的C++11序列化库,易于使用且性能良好。
sudo apt-get update
sudo apt-get install libboost-all-dev
#include <cereal/archives/json.hpp>
#include <cereal/types/vector.hpp>
#include <fstream>
#include <iostream>
#include <vector>
class Person {
public:
std::string name;
int age;
template<class Archive>
void serialize(Archive & archive) {
archive(name, age);
}
};
int main() {
std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}};
// 序列化到文件
{
std::ofstream ofs("people.json");
cereal::JSONOutputArchive oarchive(ofs);
oarchive(people);
}
// 从文件反序列化
std::vector<Person> loaded_people;
{
std::ifstream ifs("people.json");
cereal::JSONInputArchive iarchive(ifs);
iarchive(loaded_people);
}
// 打印反序列化后的数据
for (const auto& person : loaded_people) {
std::cout << person.name << " " << person.age << std::endl;
}
return 0;
}
std::ofstream和std::ifstream如果你只需要简单的序列化和反序列化,可以使用标准库的文件流。
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
struct Person {
std::string name;
int age;
};
void serialize(const std::vector<Person>& people, const std::string& filename) {
std::ofstream ofs(filename);
for (const auto& person : people) {
ofs << person.name << " " << person.age << "\n";
}
}
std::vector<Person> deserialize(const std::string& filename) {
std::vector<Person> people;
std::ifstream ifs(filename);
std::string line;
while (std::getline(ifs, line)) {
Person person;
sscanf(line.c_str(), "%s %d", &person.name[0], &person.age);
people.push_back(person);
}
return people;
}
int main() {
std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}};
// 序列化到文件
serialize(people, "people.txt");
// 从文件反序列化
std::vector<Person> loaded_people = deserialize("people.txt");
// 打印反序列化后的数据
for (const auto& person : loaded_people) {
std::cout << person.name << " " << person.age << std::endl;
}
return 0;
}
以上是几种在Ubuntu中使用C++实现序列化的方法。根据你的需求和偏好,可以选择适合的库和方法。