2013-02-14 41 views
4

嘗試使用pair作爲visual Studio 2010下的hash_map的關鍵值。使用pair作爲視覺工作室下的hash_map的關鍵點

無法編譯它。

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    hash_map <pair<int, int>, int> months; 
    months[pair<int, int>(2,3)] = 1; 

    int d; 
    cin >> d; 

    return 0; 
} 

遇到錯誤消息:

錯誤1個錯誤C2440: '類型轉換':不能從 '常量性病::對< _Ty1,_Ty2>' 轉換爲 '爲size_t' C:\程序文件\微軟的Visual Studio 10.0 \ VC \包括\ xhash 34 1 testApplication1

我知道它probablly由於hash_map ddoesn't爲pair提供專業化。任何簡單的方法來解決它?謝謝

+0

嗯,好的工作與'的std :: map'但不是'STD: :unordered_map' – Benj 2013-02-14 15:59:29

+0

*「visual studio 2010」* - 刪除'hash_map'並使用正確的'std :: unordered_map'。儘管如此,這仍然不能解決您的問題。不幸的是,缺少'std :: pair'的散列函數是C++ 11中最大的漏洞之一(但是,至少他們在15年後意識到散列是有用的數據結構)。 – 2013-02-14 16:17:28

回答

4

你必須編寫自己的hash_compare - 功能爲你使用的對象作爲關鍵!

你的情況是它std::pair<int,int>

this後 - 也許你會得到一個更好的主意實現自己比較!

2

這裏有一個pair<int,int>散列函數對象的一個​​很簡單的例子,它應該給你足夠的啓動,以實現自己的:

using namespace std; 

class pair_hasher 
{ 
public: 
    size_t operator()(const pair<int, int> & p) const 
    { 
     return p.first*100 + p.second*10000; 
    } 
}; 

typedef unordered_map <pair<int, int>, int, pair_hasher> pair_map; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    pair_map months; 
    pair<int, int> p = make_pair<int, int>(2,3); 
    months[p] = 1; 
    cout << months[p] << endl; 

    return 0; 
}