簡體   English   中英

C ++序列化/反序列化std :: map <int,int> 從/到文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM