开发者

How to save STL map to file

开发者_运维技巧

Is it possible to save STL map to file? and I can load the file to map to save time. thanks!


Well, you can do it manually. If not, the easiest way would be to use boost.serialization, that comes with support for all standard containers:

std::ofstream ofs("output_file");

// create class instance
std::map<int,string> whatever;

// populate map.

// save data to archive
{
    boost::archive::text_oarchive oa(ofs);
    // write map instance to archive
    oa << whatever;
    // archive and stream closed when destructors are called
}

You can see how the reverse works (reading from archive), and also that you can use also binary archives. (You'll need a bunch of includes too, but you can get these from the documentation.)


template<class A, class B>
void fn SaveMap(std::map<A, B>& savethismap)
{
  ofstream tfStream("filename");
  tfStream << savethismap.size() << std::endl;
  typedef std::pair<const A, B>& pr;
  BOOST_FOREACH(pr p, savethismap)
  {
     tfStream >> p.first << std::endl << p.second << std::endl;
  }
  tfStream.close();
}

This saves everything. I templated this just so you can specialize, I tried it using A : std::string and B : int . It worked fine for me.

Hope it helps.


You can do it with serialization. Here you can find a tutorial explaining how to do it: http://www.functionx.com/cpp/articles/serialization.htm

However, I'm not sure if it will save you time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜