gpt4 book ai didi

c++ - Boost::序列化 std::unordered_map>

转载 作者:行者123 更新时间:2023-11-28 02:18:23 29 4
gpt4 key购买 nike

我正在尝试使用 boost::serialize 序列化一个简单的 std::unordered_map>。我设法保存 map 就好了。当我尝试加载它时出现问题。这是我编写的代码:

    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;

我加载 map 的代码是这样的:

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

我得到了“ia >> map;”这一行的 boost::archive::archive_exception。该异常是一个“unregistered_cast”异常,根据 boost 文档指出:

// 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).

感谢任何帮助。谢谢!

最佳答案

您很可能/还/序列化了其他一些多态类型。一个 SSCCE 示例显示这适用于 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();
}

如果还有问题,请检查

  • Undefined Behaviour
  • 对于 ABI 问题(是否使用与主程序相同的编译器/库版本和标志编译 boost)

关于c++ - Boost::序列化 std::unordered_map<double, std::vector<double>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334820/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com