在C++ 11中構造unordered_map時,對鍵和值的數據類型有什麼限制?unordered_map的鍵
我試圖創建這樣的:
unordered_map<vector<int>, int>
這給了我一個編譯錯誤。我是否需要編寫自己的hasher?
在C++ 11中構造unordered_map時,對鍵和值的數據類型有什麼限制?unordered_map的鍵
我試圖創建這樣的:
unordered_map<vector<int>, int>
這給了我一個編譯錯誤。我是否需要編寫自己的hasher?
std::unordered_map
的密鑰需要通過專門std::hash
的哈希實現。
標準的專業化這是在STL中定義的基本類型有:
template<> struct hash<bool>;
template<> struct hash<char>;
template<> struct hash<signed char>;
template<> struct hash<unsigned char>;
template<> struct hash<char16_t>;
template<> struct hash<char32_t>;
template<> struct hash<wchar_t>;
template<> struct hash<short>;
template<> struct hash<unsigned short>;
template<> struct hash<int>;
template<> struct hash<unsigned int>;
template<> struct hash<long>;
template<> struct hash<long long>;
template<> struct hash<unsigned long>;
template<> struct hash<unsigned long long>;
template<> struct hash<float>;
template<> struct hash<double>;
template<> struct hash<long double>;
template< class T > struct hash<T*>;
對於一切你需要編寫自己的散列和/或使用boost::hash
。
而且爲Tony D「的評論說:
您可以指定哈希函數作爲第三個模板參數,如果你喜歡 。另外,運算符==也必須可用於鍵對象,或指定爲第四個模板參數的比較。
對於一些有用的信息+1,但是「通過專門化std :: hash'」並不完全正確,因爲如果您願意,可以將散列函數指定爲第三個模板參數。另外,'=='也必須可用於鍵對象,或者比較指定爲第四個模板參數.... – 2014-10-03 10:57:36
@MarcoA。我也想找出「何時」寫一個自定義的哈希。 – ibp73 2014-10-03 09:25:04
當你有一個沒有定義的類型,或者除非你不滿意(不管什麼原因),默認的類型是 – 2014-10-03 09:27:12
@MarcoA。如何找出未定義的類型?我無法在任何地方找到完整的基本類型列表。 – ibp73 2014-10-03 10:37:34