【问题标题】:how to serialize map of vector with map value如何用地图值序列化矢量地图
【发布时间】:2021-07-24 10:50:06
【问题描述】:

我正在尝试使用 boost 来序列化这种数据类型:

map <vector<vector<char>>, map <char, int>>

但我很难找出如何序列化它。我要做的是保存这个变量,因为它是训练模型的答案,然后加载它。如果有另一种方法可以将此变量保存到文件中,那么读取它没问题

【问题讨论】:

    标签: c++ dictionary vector serialization boost


    【解决方案1】:

    很多方法,但是自从你标记了 boost:

    活在 Coliru 上

    #include <boost/serialization/map.hpp>
    #include <boost/serialization/vector.hpp>
    #include <boost/archive/text_oarchive.hpp>
    #include <boost/archive/text_iarchive.hpp>
    #include <fstream>
    #include <iostream>
    
    using TrainingModel =
        std::map<std::vector<std::vector<char>>, std::map<char, int>>;
    
    void save(std::string filename, TrainingModel const& model) {
        std::ofstream ofs(filename);
        boost::archive::text_oarchive oa(ofs);
        oa << model;
    }
    
    TrainingModel load(std::string filename) {
        TrainingModel model;
        std::ifstream ifs(filename);
        boost::archive::text_iarchive ia(ifs);
        ia >> model;
        return model;
    }
    
    int main() {
        TrainingModel model{
            {{{'a', 'b', 'c'}, {'d', 'e', 'f'}}, {{'A', 1}, {'B', 2}}},
            {{{'g', 'h', 'i'}, {'j', 'k', 'l'}}, {{'G', 7}, {'H', 8}}},
            {{{'m', 'n', 'o'}, {'p', 'q', 'r'}}, {{'M', 13}, {'N', 14}}},
        };
    
        save("model.dat", model);
        TrainingModel cloned = load("model.dat");
    
        std::cout << "Clone equal? " << std::boolalpha << (model == cloned) << "\n";
    }
    

    打印

    Clone equal? true
    

    【讨论】:

      猜你喜欢
      • 2011-10-30
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多