How to create a mapped file with a std :: map

1

I'm trying to use a std :: map that allocates objects within a mapped file using boost, with a vector worked but with a non map

#include <boost/interprocess/managed_mapped_file.hpp>
#include <map>
#include <iostream>
namespace bi = boost::interprocess;
using namespace std;

int main() {
    std::string vecFile = "file_mapped.dat";
    bi::managed_mapped_file file_vec(bi::open_or_create,vecFile.c_str(), 1000);

    typedef bi::allocator<std::pair<string, string>, bi::managed_mapped_file::segment_manager> int_alloc;
    typedef std::map<string, string, int_alloc>  MyMap;

    MyMap * mapptr = file_vec.find_or_construct<MyMap>("mymap")(file_vec.get_segment_manager());

    (*mapptr)["aaa"] = "olahd";
    mapptr->insert({"bbb", "98473"});

    for(auto& par: *mapptr)
        std::cout << par.second << std::endl;
}
    
asked by anonymous 11.07.2017 / 16:17

1 answer

1

Here are two routines that illustrate how to serialize and deserialize a std::map of / to a text file. All in the C++11 pattern and using the boost library:

Recording (serializar.cpp):

#include <string>
#include <map>
#include <fstream>

#include <boost/serialization/map.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

typedef std::map<std::string, double> MyMap;

int main()
{
    MyMap map = {{"Pi",3.14159}, {"Proporcao Aurea",1.61803}, {"Constante de Euler",2.71828}};
    std::fstream fs( "mapped.txt", std::ios::out );
    boost::archive::text_oarchive oarch(fs);

    /* Exibe conteudo do mapa */
    for ( auto &i : map )
        std::cout << i.first << " = " <<  i.second << std::endl;

    /* Grava mapa no arquivo */
    oarch << map;

    return 0;
}

Compiling:

$ g++ serializar.cpp -std=c++11 -lboost_serialization -o serializar

Read (deserializar.cpp):

#include <string>
#include <map>
#include <fstream>

#include <boost/serialization/map.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

typedef std::map<std::string, double> MyMap;

int main()
{
    MyMap map;
    std::fstream fs( "mapped.txt" );
    boost::archive::text_iarchive iarch(fs);

    /* Le mapa do arquivo */
    iarch >> map;

    /* Exibe conteudo do mapa */
    for ( auto &i : map )
        std::cout << i.first << " = " <<  i.second << std::endl;

    return 0;
}

Compiling:

$ g++ deserializar.cpp -std=c++11 -lboost_serialization -o deserializar
    
11.07.2017 / 20:35