我想創建一個具有char*
作爲關鍵字和vector<int>
作爲value
的unordered_map。我從前面的問題中得知,STL沒有提供char*
的散列函數。C++:爲什麼我的散列函數爲unordered_map <char *,向量<int>>工作?
我把第一個實現從這個網站: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);
最終地圖,而不是具有大小兩者的矢量,其中該矢量的每個元素是一個「TEMP」鍵0或1它有一個名爲「溫度」,並在每個鍵的矢量的兩個鍵尺寸1.
這裏是詳細的圖片:
我怎樣才能避免這種情況發生?預先感謝你
爲什麼不使用'std :: string'?你的哈希表會泄漏內存。 – jxh 2013-03-27 18:03:09
使用STD某種原因:: string的給了我非常緩慢的執行時間 我想看看是否有什麼就用字符*雖然我有一種感覺,什麼都不會改變... – ksm001 2013-03-27 18:05:49