is it possible serialize any STL class including std::string? I've a sets of std::strings and I'm trying to write them into file and load them back into std::set.
Serialization is the process of writing or reading an object to or from a persistent storage medium such as a disk file. Serialization is ideal for situations where it is desired to maintain the state of structured data (such as C++ classes or structures) during or after execution of a program.
Serialization is the process of converting a data object—a combination of code and data represented within a region of data storage—into a series of bytes that saves the state of the object in an easily transmittable form.
The library Boost. Serialization makes it possible to convert objects in a C++ program to a sequence of bytes that can be saved and loaded to restore the objects. There are different data formats available to define the rules for generating sequences of bytes. All of the formats supported by Boost.
Yes, it's possible. With boost.serialization, for example.
For STL, read corresponding tutorial section
An example of using boost::serialization to serialize an STL type
#include <map>
#include <fstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/map.hpp>
int main(int argc,char** argv) {
std::ofstream s("tmp.oarchive");
boost::archive::text_oarchive oa(s);
std::map<int,int> m;
m[1] = 100;
m[2] = 200;
oa << m;
}
Compile with
g++ -lboost_serialization myfile.cc
Note that
#include <boost/archive/text_iarchive.hpp>
must be before any other boost
serialization includes.If you just want to write a std::set<std::string>
to a file and read it back out, and your project doesn't already use Boost, you might try something simple:
ofstream file("file.txt");
copy(theSet.begin, theSet.end(), ostream_iterator<string>(file, "\n"));
This will simply write the strings, one per line, into a text file. Then to read them:
ifstream file("file.txt");
string line;
while(getline(file, line))
theSet.insert(line);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With