是否可以将STL map保存到文件中?我想加载文件以便节省时间。谢谢!
是否可以将STL map保存到文件中?我想加载文件以便节省时间。谢谢!
好的,您可以手动完成此操作。如果不想这样做,最简单的方法是使用boost.serialization
,它支持所有标准容器:
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
}
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();
}
这个保存了所有内容。我将其模板化,以便您可以进行专业化,我尝试使用A:std :: string和B:int进行了测试。对我来说效果很好。
希望能有所帮助。
boost.serialization
)相比,性能(读/写速度等)如何?另外,一些想法:1)通常我们可以使用基于范围的for循环而不是BOOST_FOREACH。2)错别字:>>
的方向。 - starriet