Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization of STL Class

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.

like image 325
user963241 Avatar asked Dec 12 '10 15:12

user963241


People also ask

What is serialization in MFC?

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.

What is meant by serialization?

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.

What is Boost serialization?

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.


3 Answers

Yes, it's possible. With boost.serialization, for example.

For STL, read corresponding tutorial section

like image 180
Abyx Avatar answered Sep 18 '22 12:09

Abyx


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

  1. The #include <boost/archive/text_iarchive.hpp> must be before any other boost serialization includes.
  2. You need to include a header for the STL type you want to archive.
like image 24
Elazar Leibovich Avatar answered Sep 20 '22 12:09

Elazar Leibovich


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);
like image 34
John Zwinck Avatar answered Sep 19 '22 12:09

John Zwinck