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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With