Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Serialize/Deserialize std::map<int,int> from/to file

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.

like image 889
tmighty Avatar asked Apr 18 '13 06:04

tmighty


2 Answers

use boost::serialization for serialize in one line. Header for it:

boost/serialization/map.hpp

Code example

#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;
}

Output:

g++ -o new new.cpp -std=c++0x -lboost_serialization
./new
1

for file simply use std::ifstream/std::ofstream instead of std::stringstream and may be binary_archive, instead of text_archive.

like image 62
ForEveR Avatar answered Oct 08 '22 14:10

ForEveR


There isn't a one-liner to serialize a map. You would need to write each key/value pair individually. This really isn't much more complicated than a for loop, though.

Using boost, there might be a way, but I'm not familiar with the exact APIs.

like image 1
StilesCrisis Avatar answered Oct 08 '22 14:10

StilesCrisis