2011-02-02 10 views
16

マイコード:ペア<int,int>ペア

typedef pair<int,int> Pair 
    tr1::unordered_map<Pair,bool> h; 
    h.insert(make_pair(Pair(0,0),true)); 

Erorr

undefined reference to `std::tr1::hash<std::pair<int, int> >::operator()(std::pair<int, int>) const' 

私は修正する必要が何か?

おかげ

答えて

23

Key = std::pair<int, int>std::tr1::hash<Key>のための専門がないためです。 tr1::unordered_map<Pair,bool> h;と宣言する前に、std::tr1::hash<Key>Key = std::pair<int, int>に特化する必要があります。 これは、stdpair<int, int>をハッシュする方法を知らないために発生します。

同じ問題にstd::tr1::hash<>

template <> 
struct std::tr1::hash<std::pair<int, int> > { 
public: 
     size_t operator()(std::pair<int, int> x) const throw() { 
      size_t h = SOMETHING;//something with x 
      return h; 
     } 
}; 
+0

+1、 ' unordered_map'はハッシュテーブルである。 – vz0

+15

私がライブラリで使用するために特化し、ライブラリで使用するために特殊化し、定義が同一でない場合、ライブラリがリンクされているときに未定義の動作が発生するので、残念です。 'std :: tr1 :: hash'は多少過小ですが、可能であれば3番目のテンプレートパラメータとして' unordered_map'にカスタムHashクラスを指定する方が良いでしょう。 –

+1

@スティーブ:いいえ、痛みは、ゲイン: –

0

蘭を専門とする方法の例があり、次のとおりです。

unordered_map <pair<x, y>, z> m1; 

いくつかの回避策は以下のとおりです。

unordered_map <stringxy, z> m1; 
// the first and second of the pair merged to a string 
// though string parsing may be required, looks same complexity overall 

unordered_multimap <x, pair<y, z>> m1; 
// second of the pair of the key went into value. 
// time complexity slightly increases 

deque<deque<x>> d1; 
// here x & y are of same type, z is stored as: d1[x][y] = z 
// space required is x * y, however time complexity is O(1)