2017-06-13 87 views
0

我想存儲一個結構到一個映射使用哈希函數的關鍵。在創建兩個相同的對象時,我從散列函數獲得了相同的密鑰,但每個元素仍然插入到映射中。插入不從哈希函數檢索密鑰

這裏是我的代碼:

// 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

我的意思是,兩個記錄被添加到地圖中,而應該只有一個,因爲關鍵是相同的 – Batmax

+0

爲什麼說這兩個記錄都被添加?在一些情況下,請參閱下面的答案 –

回答

0

我編譯你的代碼,並打印,在您的地圖元素的數,您插入兩次相同的元素後:

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

所以你的代碼是你希望的運行/想要它。

您如何達到您認爲插入2次的程度?

+0

我的結構實際上更復雜(包括指針)。也許問題來自 – Batmax

+0

@Batmax:然後請添加該代碼。 –

0

問題是由於一個關鍵變量。它的類型是char [],比較函數工作不正常。使用strcmp()修復了這個問題。 謝謝!