2010-09-02 48 views
2
I want to serialize a hash map to a file and de-serialize it later on. 

#include <boost/serialization/hash_map.hpp> 
#include <boost/filesystem/fstream.hpp> 
#include <hash_map> 

class A: virtual public B { 
public: 
    friend class boost::serialization::access; 
    stdext::hash_map<std::string, myClass> myClassHashTable; 
    template <class Archive> 
    void serialize(Archive &ar, const unsigned int version) 
    { 
     ar & myClassHashTable; 
    } 
}; 

void A::serializedToDisk() 
{ 
     boost::filesystem::path finalPath(SOME_CONSTANT); 
     // code to create boost::filesystem::ifstream ofs object 
     boost::archive::text_oarchive oa(ofs); 
     oa << myClassHashTable; 
} 
void A::restoreFromDisk() 
{ 
    boost::filesystem::path finalPath(SOME_CONSTANT); 
    // code to create boost::filesystem::ifstream ifs object 
     boost::archive::text_iarchive ia(ifs); 
     ia >> myClassHashTable; 
} 

但我得到一個錯誤 -序列化stdext ::使用的hash_map升壓串行化庫

error C2039: 'serialize' : is not a member of 'stdext::hash_map<_Kty,_Ty>' 

我在網上搜索了這個錯誤,但並沒有得到太多的幫助。另外,我檢查了我的boost安裝序列化/ hash_map.hpp中有一個serialize()函數。相同的代碼可用於序列化std::deque。任何人都可以告訴我,我應該如何改變它來編譯它?

+0

不是你所需的東西,但谷歌Sparsehash圖書館地圖來與一些內置的序列化支持,儘管與Boost序列化完全分開。 – doublep 2010-09-07 20:09:03

+0

http://stackoverflow.com/questions/23764249/c-boost-serialization-error-for-hash-map-with-custom-objects-as-key/23768271#23768271 – sehe 2015-01-10 16:57:15

回答

4

首先,在代碼頂部插入#define BOOST_HAS_HASH

這改變你的編譯錯誤:

「錯誤C2039: '調整':是不是 'stdext ::的hash_map < _Kty,_Ty>' 中的一員」。 :D

接下來,如果你評論你的恢復功能,你會看到你的代碼工作正常,並輸出! <好>

但問題是關於編譯器之間的不兼容性。 不幸的是,在'MSVS'和'GCC'中的hash_map的實現是不同的,並且resize是這種差異的一個例子。


接下來解決這個新問題, 只是#include boost/serialization/map.hpphash_collections_load_imp.hpp評論s.resize(bucket_count);(它錯誤)