【问题标题】:How to serialize a (nested) map to a variable using boost?如何使用boost将(嵌套)映射序列化为变量?
【发布时间】:2011-10-20 01:45:21
【问题描述】:

我在一个类中声明了一个映射,如下所示:

class Example {
    public:
        Example()
        {
            std::map< std::string, std::string > map_data;
            map_data["LOCATION"] = "USA";
            map_data["WEBSITE"] = "http://www.google.com/";

            custom_map["nickb"] = map_data;
        }
        std::map< std::string, std::map< std::string, std::string > > get_map() { return custom_map; }
    private:
        std::map< std::string, std::map< std::string, std::string > > custom_map;

        friend class boost::serialization::access;
        template<class Archive>
        void serialize( Archive &ar, const unsigned int version)
        {
            ar & BOOST_SERIALIZATION_NVP( custom_map);
        }
};

而且我希望能够使用 boost 将映射序列化为变量。

这些示例似乎正在序列化整个类,我不需要这样做。他们也在写入文件,这对我来说似乎效率低下,因为我不需要将地图的状态存档到文件中,只需以以后可以恢复的方式表示它。

现在我有这个来保存地图:

// Create an Example object
Example obj;

// Save the map
std::stringstream outstream( std::stringstream::out | std::stringstream::binary);
boost::archive::text_oarchive oa( outstream);
oa << obj; // <-- BOOST SERIALIZATION STATIC WARNING HERE

// Map saved to this string:
std::string saved_map = outstream.str();

然后这个来恢复它:

// Now retore the map
std::map< std::string, std::map< std::string, std::string > > restored_map;
std::stringstream instream( saved_map, std::stringstream::in | std::stringstream::binary);
boost::archive::text_iarchive ia( instream);
ia >> restored_map;

std::map< std::string, std::string > map_data = restored_map.find( "nickb")->second;
std::cout << "nickb " << map_data["LOCATION"] << " " << map_data["WEBSITE"] << std::endl;

但它不起作用。谁能给我一些提示或告诉我如何序列化和恢复地图?

谢谢。

编辑: 我已经更详细地更新了我的示例,并考虑了 K-ballo 和 Karl Knechtel 的回答(谢谢!)。这已经解决了几乎所有的错误,除了一个错误,这是上面注释行中的 boost 序列化静态警告。警告是:

[Warning] comparison between signed and unsigned integer expressions 

知道如何解决此警告以便编译吗?谢谢!

编辑: 我的问题是双重的: 我需要添加:BOOST_CLASS_TRACKING(例如,track_never) 我正在序列化整个班级,并试图反序列化地图。

【问题讨论】:

  • 我用一个更好的例子更新了这个问题,包括来自 Karl Knechtel 和 K-ballo 的 cmets。谢谢!
  • 警告不会(通常)阻止编译。它实际上没有编译吗?如果是这样,它真的只是一个警告吗?
  • 正确,我已将 -Wall 传递给编译器,并且我的 IDE 在发出警告时停止编译。删除 -Wall 允许它编译,但会崩溃(没有输出)。

标签: c++ boost map boost-serialization


【解决方案1】:

看起来您有两个完全独立的stringstream 对象:其中一个接收数据,另一个(没有基础字符串数据)您尝试从中恢复数据。 stringstream 无论如何都不是数据存储; stringfstream 写入磁盘上的文件的方式大致相同,该文件是实际的存储空间。

获取您要保存到的流的.str(),并使用它来初始化您从中读取的流。

【讨论】:

  • 感谢您的建议 - 我更新了问题并合并了您的答案,但仍然无法编译。
【解决方案2】:

您的流的 inout 值是向后的。此外,您没有使用数据初始化输入流,因此它是空的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多