C++ unordered_map無法使用pair作爲key的解決辦法

最近在使用STL中unordered_map這種容器的時候發現無法將key設置爲pair類型,編譯報錯信息爲:

error: implicit instantiation of undefined template 'std::__1::hash<std::__1::pair<int, int> >

查了下資料才發現unordered_map中沒有針對pair的hash函數,需要手動傳入一個hash函數。hash函數的一種簡單實現如下:

struct hash_pair { 
    template <class T1, class T2> 
    size_t operator()(const pair<T1, T2>& p) const
    { 
        auto hash1 = hash<T1>{}(p.first); 
        auto hash2 = hash<T2>{}(p.second); 
        return hash1 ^ hash2; 
    } 
}; 

接下來把這個hash函數傳給unordered_map就OK了!

unordered_map<pair<int,int>, int, hash_pair> um;

因爲map容器並不需要hash函數,所以將key設置爲pair是不會報錯的。在數據量不大的情況下,也可以考慮使用map替代unordered_map,性能並不會有太大差異。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章