[英]C++ Hash function for string in unordered_map
似乎 C++ 在標准庫中沒有字符串的哈希函數。 這是真的?
在 unordered_map 中使用字符串作為鍵的工作示例是什么,它可以與任何 C++ 編譯器一起使用?
C ++ STL提供的模板特化的std::hash
的各種串類。 您可以將std::string
指定為std::unordered_map
鍵類型:
#include <string>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, int> map;
map["string"] = 10;
return 0;
}
我今天遇到了這個問題(實際上是wstring
,而不是string
,但它是一樣的):在unordered_map
使用wstring
作為鍵會產生一個關於沒有哈希函數可用於該類型的錯誤。
我的解決方案是添加:
#include <string>
信不信由你,如果沒有#include
指令,我仍然可以使用wstring
類型,但顯然不是像散列這樣的輔助函數。 只需添加上面的包含即可修復它。
實際上,有std::hash<std::string>
但是你可以如何使用另一個哈希函數:
struct StringHasher {
size_t operator()(const std::string& t) const {
//calculate hash here.
}
}
unordered_map<std::string, ValueType, StringHasher>
如果您有一個CustomType
並且您想插入 STL 基礎結構,這就是您可以做的。
namespace std
{
//namespace tr1
//{
// Specializations for unordered containers
template <>
struct hash<CustomType> : public unary_function<CustomType, size_t>
{
size_t operator()(const CustomType& value) const
{
return 0;
}
};
//} // namespace tr1
template <>
struct equal_to<CustomType> : public unary_function<CustomType, bool>
{
bool operator()(const CustomType& x, const CustomType& y) const
{
return false;
}
};
} // namespace std
如果您隨后想創建一個std::unordered_map<CustomType>
,STL 將找到hash
和equal_to
函數,而您無需對模板執行任何操作。 這就是我喜歡編寫支持無序數據結構的自定義相等比較器的方式。
就我而言,這真的很讓人分心。
我有一個類型 X,我為它實現了const& X的散列,並在某處使用了它
std::unordered_map<const X, int> m_map;
然后我想要另一個地圖,其中鍵是X
類型並且做了:
std::unordered_map<X, int> map_x;
注意第二種情況下const
的缺失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.