2013-04-07 7 views
14

unordered_set<Interval>を作成する次のコードがあります。これはうまくコンパイルされます。私はこのコードを使用して挿入しようとするとカスタムハッシュ関数を使用してunordered_setに挿入する

struct Interval { 
    unsigned int begin; 
    unsigned int end; 
    bool updated; //true if concat. initially false 
    int patternIndex; //pattern index. valid for single pattern 
    int proteinIndex; //protein index. for retrieving the pattern 
}; 

struct Hash { 
    size_t operator()(const Interval &interval); 
}; 


size_t Hash::operator()(const Interval &interval){ 
    string temp = to_string(interval.begin) + to_string(interval.end) + to_string(interval.proteinIndex); 
    return hash<string>()(temp); 
} 

unordered_set<Interval, string, Hash> test; 

しかし、私はコンパイルできません。

for(list<Interval>::iterator i = concat.begin(); i != concat.end(); ++i){ 
    test.insert((*i)); 
    } 

また、私はこの問題は、エラーメッセージからが何であるかを判断することはできません。ここで

はサンプルです:

note: candidate is: 
note: size_t Hash::operator()(const Interval&) 
note: candidate expects 1 argument, 2 provided 

私が唯一の1つの引数を提供すると思った...

誰もが私の挿入コードの問題を参照してくださいしていますか?可能であれば、お手伝いをしてください。私はかなりの間、今のところ解決策を探していました。

編集:ここでは

は、新しいインスタンス生成コードです:しかしunordered_set<Interval, Hash> test; 、私はまだエラーメッセージのスルーを受けています。例:

note: candidate is: 
note: size_t Hash::operator()(const Interval&) <near match> 
note: no known conversion for implicit ‘this’ parameter from ‘const Hash*’ to ‘Hash*’ 
+0

私の回答が更新されました。あなたの編集に記載されている問題を解決するはずです –

+0

http://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as- the-key –

答えて

25

まず問題:あなたはunordered_set<>クラステンプレートのあなたのインスタンス化のための第2のテンプレート引数としてstringを渡している

The second argument should be the type of your hasher functorstd::stringは呼び出し可能なオブジェクトではありません。おそらく、書くためのもの

:これらは、C++標準ライブラリのアルゴリズムの名前であるため、また

unordered_set<Interval, /* string */ Hash> test; 
//      ^^^^^^^^^^^^ 
//      Why this? 

、私は、あなた(メンバー)の変数のためのbeginend以外の名前を使用してお勧めします。

第二の問題:

struct Hash { 
    size_t operator() (const Interval &interval) const { 
    //           ^^^^^ 
    //           Don't forget this! 
    string temp = to_string(interval.b) + 
        to_string(interval.e) + 
        to_string(interval.proteinIndex); 
    return (temp.length()); 
    } 
}; 

第三の問題:最後に

、あなたはstd::unordered_setがしたい場合は

あなた数子があるべきようにするには、that the hasher function should be qualified as const、心に留めておく必要がありますタイプIntervalのオブジェクトで作業できるようにするには、ハッシュと一致する等価演算子を定義する必要があります関数。デフォルトでは、std::unordered_setクラステンプレートの3番目のパラメータとして型引数を指定しない場合は、operator ==が使用されます。

現在、クラスIntervalにはoperator ==のオーバーロードがありませんので、ご提供ください。たとえば、次のように

inline bool operator == (Interval const& lhs, Interval const& rhs) 
{ 
    return (lhs.b == rhs.b) && 
      (lhs.e == rhs.e) && 
      (lhs.proteinIndex == rhs.proteinIndex); 
} 

結論:

上記のすべての変更後は、あなたのコードは、このlive exampleでコンパイル見ることができます。

+0

私は参照してください。助けてくれてありがとう! – user2052561

+0

@ user2052561:修正をさらに含むように答えを更新しました –

+0

うわー!どうもありがとう。これは私の初めての 'unordered_set'sを使用していました... – user2052561

関連する問題