簡體   English   中英

C ++:為什么不是unordered_map的哈希函數 <char*, vector<int> &gt;工作?

[英]C++: Why isn't my hash function for the unordered_map<char*, vector<int>> working?

我想創建一個unordered_map,其中char*作為鍵, vector<int>作為value 我從之前的問題中了解到,STL沒有提供char*哈希函數。

我從這個網站上獲得了第一個實現: http//www.cse.yorku.ca/~oz/hash.html

所以我的main.cpp文件插入了以下代碼:

namespace std
{
   template<>
   struct hash<char*>: public std::unary_function<char *, size_t>
   {
      size_t operator()(char * str) const{
      size_t hash = 5381;
      int c;

      while(c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

      return hash;

     }
  };
}

然后我創建了一個unordered_map變量:

std::unordered_map<char *, vector<int>> test;

但是,如果我通過這樣做兩次插入值“temp”:

std::unordered_map<char *, vector<int>> test;
char *t1 = new char[5];
strcpy(t1, "temp");
char *t2 = new char[5];
strcpy(t2, "temp");
vector<int>& ptr = test[t1];
ptr.push_back(0);
vector<int>& ptr2 = test[t2];
ptr2.push_back(1);

最終的映射而不是一個帶有大小為2的向量的“temp”鍵,其中向量的每個元素是0或1,它有兩個名為“temp”的鍵,每個鍵中有一個大小為1的向量。

這是詳細的圖片: 在此輸入圖像描述

我怎么能避免這種情況發生? 先感謝您

這對散列函數來說不是問題,它是char*相等的問題。 您依賴於指針比較,並且您可以從調試器監視變量中看到,各種“臨時”文字的指針具有不同的位置,因此不相等。

您需要定義一個實際執行字符串比較的相等函數,並將其與unordered_map一起使用。

或者,不要使用char*作為鍵,而是使用std::string ,並完全避免這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM