我在一个类中声明了一个地图,如下所示:
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(Example, track_never) 我正在序列化整个班级,并试图反序列化地图。