![](/img/trans.png)
[英]How to serialize/deserialize std::map<int, MyObject> to/from json in C++
[英]C++ Serialize/Deserialize std::map<int,int> from/to file
我有一個std :: map。
我想知道我是否可以使用fwrite將其寫入文件(也可以從文件中讀取),如果我需要分別寫入/讀取每個值。
我希望,因為沒有什么特別的,這可能是可能的。
使用boost::serialization
在一行中進行序列化。 標題:
boost/serialization/map.hpp
代碼示例
#include <map>
#include <sstream>
#includ <iostream>
#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循環復雜得多。
使用boost,可能有一種方法,但我不熟悉確切的API。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.