How to create a mapped file with an Std::map

Asked

Viewed 424 times

1

I’m trying to use a Std::map that allocates objects within a file mapped using boost, with a vector worked but with a map not

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

1 answer

1

Follow two routines illustrating how to serialize and deserialize a std::map from/to a text file. All standard C++11 and using the library boost:

Recording (serialize.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

Reading (deserialize.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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.