2017-06-13 9 views
0

キーのハッシュ関数を使用して構造体をマップに格納しようとしています。 2つの同一のオブジェクトを作成する場合、ハッシュ関数から同一のキーを取得しますが、各要素はまだマップに挿入されています。ここでinsertはハッシュ関数からキーを取得しません

は私のコードです:私のメインプログラムの

// Key 
struct GridrecordKey { 
    // Keys 
    double key1; 
    double key2; 
    ... 

    GridrecordKey() { 
     key1 = 0; 
     key2 = 0; 
     ... 
    } 

    bool operator==(const GridrecordKey &other) const { 
     return (key1 == other.key1 
      && key2 == other.key2); 
    } 
}; 

// Hash function 
struct GridrecordKeyHasher 
{ 
    std::size_t operator()(const GridrecordKey& k) const 
    { 
     using boost::hash_value; 
     using boost::hash_combine; 

     // Start with a hash value of 0 . 
     std::size_t seed = 0; 

     hash_combine(seed, hash_value(k.key1)); 
     hash_combine(seed, hash_value(k.key2)); 

     // Return the result. 
     return seed; 
    } 
}; 

// Record 
struct gridrecord { 
    double element1; 
    double element2; 
... 
}; 

はサンプル:

int main() { 
     GridrecordKey key; // The key 
     gridrecord record; // The record 
     unordered_map<GridrecordKey, gridrecord, GridrecordKeyHasher> map; // The map 

     // Modify the key and insert record into map 
     key.key1 = 1; 
     map.insert({ key, record }); 

     // Keep the same key and try to insert another record into the map 
     key.key1 = 1; 

     // Here the record is added to the map while it should't as this 
     // key already exist 
     auto x = map.insert({ key, record }); 
    } 

事前に感謝します!

+0

各要素がまだ挿入されているとはどういう意味ですか?キーが重複しているにもかかわらず行が実行される –

+0

キーが同じであるために2つのレコードがマップに追加されるということです。 – Batmax

+0

なぜ2つのレコードが両方とも追加されているとしますか?いくつかのコンテキストについては、以下の回答を参照してください。 –

答えて

0

私はあなたのコードをコンパイルして、2回同じ要素を挿入した後、マップ内にある要素の数を印刷:/あなたは予想通り

std::cout << map.size() << std::endl; 
--> 1 

だからあなたのコードが実行されているが、それを望んでいました。

2回挿入されたと思いますか?

+0

My Structは実際にはもっと複雑です(ポインタも含む)。たぶん問題はそれから来た – Batmax

+0

@Batmax:それではコードを追加してください。 –

0

この問題はキー変数によるものです。その型はchar []であり、比較関数は正しく機能しませんでした。 strcmp()を使用して問題を修正しました。 ありがとうございました!

関連する問題