boost序列化vector

#include 
#include 
#include 
#include 
#include 
#include 
#include 

class MyClass {
public:
    MyClass() : name(""), value(0) {}
    MyClass(const std::string& n, int v) : name(n), value(v) {}

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version) {
        ar & name;
        ar & value;
    }

    void print() const {
        std::cout << "Name: " << name << ", Value: " << value << std::endl;
    }

private:
    std::string name;
    int value;
};

int main() {
    // 创建一个包含 MyClass 对象的 vector
    std::vector<MyClass> myVector;
    myVector.push_back(MyClass("Object1", 42));
    myVector.push_back(MyClass("Object2", 55));
    myVector.push_back(MyClass("Object3", 77));

    // 序列化 vector 到文件
    {
        std::ofstream file("vector_serialize.txt");
        boost::archive::text_oarchive ar(file);
        ar << myVector;
    }

    // 反序列化 vector 从文件
    {
        std::ifstream file("vector_serialize.txt");
        boost::archive::text_iarchive ar(file);
        std::vector<MyClass> loadedVector;
        ar >> loadedVector;

        // 打印反序列化后的数据
        for (const auto& obj : loadedVector) {
            obj.print();
        }
    }

    return 0;
}

你可能感兴趣的:(boost,c++)