Serialization of complex structures in C++

前端 未结 2 1004
青春惊慌失措
青春惊慌失措 2020-12-17 00:14

I\'m trying to serialize a set of structs in C++. This works great for all data except a vector contained in my struct. I can write the data to disk, and then read all data

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 00:52

    Probably the simplest version of serializing a vector that stands a chance of working is something like:

    your_stream << your_vector.size();
    std::copy(your_vector.begin(), your_vector.end(),
         std::ostream_iterator(your_stream, "\n"));
    

    Reading it back goes something like:

    size_t size;
    your_stream >> size;
    vector_two.resize(size);
    for (size_t i=0; i> vector_two[i];
    

    Note that this is not particularly efficient -- in particular, it (basically) assumes the data will be stored in text format, which is often fairly slow and takes up extra space (but is easy to read, manipulate, etc., by outside programs, which is often useful).

提交回复
热议问题