2010-10-25 29 views
2

由於std::pair<std::string, unsigned int>沒有爲__gnu_cxx哈希映射定義,我如何使用std::pair<std::string, unsigned int>類型的鍵和std::pair<int, CBTNODE>類型的值創建__gnu_cxx哈希映射? (CBTNODEtypedeftypedef int CBTNODE帶有std :: pair類型的鍵的__gnu_cxx哈希映射<std :: string,unsigned int>?

如果有可能,我真的想替換std::pair<std::string, unsigned int>與一個typedef-ED INDEXtypedef std::pair<std::string, unsigned int> INDEX

任何幫助將非常感激!

Z.Zen

回答

3

這似乎編印了正確的答案(1):

#include <hash_map> 
#include <utility> 
#include <string> 
#include <iostream> 

typedef int CBTNODE; 
typedef std::pair<std::string, unsigned int> INDEX; 
typedef std::pair<int, CBTNODE> Element; 

struct pairhash{ 
    size_t operator()(const INDEX &p) const { 
     return 
      __gnu_cxx::hash<const char*>()(p.first.c_str())^
      __gnu_cxx::hash<unsigned int>()(p.second); 
    } 
}; 

int main() { 
    __gnu_cxx::hash_map<INDEX, Element, pairhash> x; 
    INDEX foo("hi", 0); 
    Element bar(1, 2); 
    x[foo] = bar; 
    std::cout << x[foo].first << "\n"; 
} 

這是一個有點乏味。問題是__gnu_cxx::hash不提供pair的專業化,或string的專業化。我相信它遵循SGI API在這裏:http://www.sgi.com/tech/stl/hash.html。因此需要pairhash(或類似的東西)來提供遺漏的散列函數。

我不怪你,因爲沒有發現,因爲編譯器錯誤,這造成了一點,這個,非常明顯。很長。

如果可以,您可能最好使用boost::unordered_map。 SGI的hash_map是一箇舊的API,從未被納入標準,由於被C++ 0x等替代等。

相關問題