C ++ Serialize / Deserialize std :: map< int,int>从/到文件 [英] C++ Serialize/Deserialize std::map<int,int> from/to file
问题描述
我有一个std :: map。
I have an std::map.
我想知道如果我可以写它到一个文件(也从文件读取)
I would like to know if I can write it to a file (and also read it from a file) in like 1 line using fwrite, or if I need to write/read each value separately.
我希望自从没有什么特别的,这可能是可能的。
I was hoping that since is nothing special, this might be possible.
推荐答案
使用 boost :: serialization
在一行中序列化。
标题:
use boost::serialization
for serialize in one line.
Header for it:
boost/serialization/map.hpp
代码示例
#include <map>
#include <sstream>
#include <boost/serialization/map.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
int main()
{
std::map<int, int> map = {{1,2}, {2,1}};
std::stringstream ss;
boost::archive::text_oarchive oarch(ss);
oarch << map;
std::map<int, int> new_map;
boost::archive::text_iarchive iarch(ss);
iarch >> new_map;
std::cout << (map == new_map) << std::endl;
}
输出:
g++ -o new new.cpp -std=c++0x -lboost_serialization
./new
1
只需使用 std :: ifstream / std :: ofstream
,而不是 std :: stringstream
,并且可以是 binary_archive
,而不是 text_archive
。
for file simply use std::ifstream/std::ofstream
instead of std::stringstream
and may be binary_archive
, instead of text_archive
.
这篇关于C ++ Serialize / Deserialize std :: map< int,int>从/到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!