6
votes

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.

4

4 Answers

10
votes

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

For STL, read corresponding tutorial section

5
votes

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.
4
votes

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);
1
votes

check this out . lite enough

STL serialization

ONLY ONE CPP FILE NEEDED

A lite serialization solution

there are several lib out there support serialization,like protobuffer, boost:serialization , too heavy for me. so I wrote this lite version.

support

  • vector
  • map
  • set
  • string
  • primitives(int,double,long,...)
  • endian support
  • nesting container support

use char instead bool in STL why

build

you can build this project by CMake. or just import serialization.h into your project.

define CHECK_ENDIAN=1 if you wanna check endian

demo

check testSerialization.cpp

comming soom

endian conversion.