简体   繁体   中英

Boost::serialization of an std::unordered_map<double, std::vector<double>>

I'm trying to serialize a simple std::unordered_map> using boost::serialize. I manage to save the map just fine. The issue occurs when I try to load it. Here is my code for writing:

    double E = 250E-4;
    std::vector<double> init_vals(2,0.0);
    std::unordered_map<double, std::vector<double>> map;
    std::ofstream ofs("energy_map");
    boost::archive::binary_oarchive oa(ofs);
    map.emplace(E, init_vals);
    oa << map;

My code to load the map is like this:

    std::ifstream ifs("energy_map");
    std::unordered_map <double, std::vector<double>> map;
    boost::archive::binary_iarchive ia(ifs);
    ia >> map;

I get a boost::archive::archive_exception for the line "ia >> map;". The exception is a "unregistered_cast" exception which according to boost documentation states:

// base - derived relationship not registered with // void_cast_register I'm not quite sure why this isn't working out cause it seems fairly simple. (I've edited the code from my original files to make it simpler, but the lines are identical to that within my code).

Any help is appreciated. Thanks!

Most likely you're /also/ serializing some other polymorphic types. A SSCCE example shows this to work on GCC:

http://paste.ubuntu.com/12963866/

#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/unordered_map.hpp>
#include <boost/serialization/vector.hpp>
#include <fstream>
#include <iostream>

void write_map() {
    std::unordered_map<double, std::vector<double> > map;
    {
        double E = 250E-4;
        std::vector<double> init_vals(2, 0.0);
        map.emplace(E, init_vals);
    }
    {
        std::ofstream ofs("energy_map");
        boost::archive::binary_oarchive oa(ofs);
        oa << map;
    }
}

void load_map() {
    std::unordered_map<double, std::vector<double> > map;
    {
        std::ifstream ifs("energy_map");
        boost::archive::binary_iarchive ia(ifs);
        ia >> map;
    }

    for (auto &p : map) {
        std::cout << p.first << " -> { ";
        std::copy(p.second.begin(), p.second.end(), std::ostream_iterator<double>(std::cout, " "));
        std::cout << "}\n";
    }
}

int main() {
    write_map();
    load_map();
}

So if you still have issues, check

  • for Undefined Behaviour
  • for ABI issues (is you boost compiled with the same compiler/library versions and flags as your main program)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM