2009-12-25 56 views
1

這一次我能夠顯示完整的代碼:C++ unordered_map問題

#include <unordered_map> 
#include <iostream> 
#include <stdlib.h> 

using namespace std; 

bool mystrcmp(const char *s1, const char *s2) { 
     int i = 0; 
     do { 
       if(s1[i] != s2[i]) 
         return false; 
     } while(s1[i++] != '\0'); 
     return true; 
} 

struct eqstr 
{ 
    bool operator()(const char* s1, const char* s2) const 
    { 
    return mystrcmp(s1, s2); 
    } 
}; 


int main(void) { 
    char buffer[5] = {'h', 'e', 'd', 'e', '\0'}; 
    unordered_map<char *, int , hash<char *> , eqstr> int_from_symbols; 
    int_from_symbols["hede"] = 1; 
    int_from_symbols["hodo"] = 2; 
    unordered_map<char *, int , hash<char *> , eqstr>::const_iterator it = int_from_symbols.find(buffer); 
    eqstr myeq; 
    if(myeq("hede",buffer)) 
     fprintf(stderr, "no problem here\n"); 
    if(it == int_from_symbols.end()) 
     fprintf(stderr, "dammit\n"); 
    else fprintf(stderr, "%d\n", int_from_symbols[buffer]); 
    return 0; 
} 

此輸出:

no problem here 
dammit 

任何想法是怎麼回事?

在此先感謝,,
厄尼爾

回答

2

問題是hash<char *>你想要什麼沒有做。它並不專門用於實際散列「字符串」,而只是將指針作爲散列返回。

添加到您的代碼,它會開始工作(雖然哈希函數並非產品質量和用於演示只):

namespace std 
{ 
    template<> 
    struct hash<char *> : public std::unary_function<char *, size_t> 
    { 
     size_t operator()(char* str) const 
     { 
      size_t h = 0; 
      for (; *str; ++str) 
       h += *str; 
      return h; 
     } 
    }; 
} 
+1

我不認爲全球專門研究'hash '這是一個好主意 - 除此之外,這可能會讓打破ODR變得非常容易。爲什麼不像往常一樣定義一個自定義函數,並將其作爲模板參數傳遞給'unordered_map'? – 2009-12-25 07:38:14

+0

請檢查您的標題,瞭解散列專業化。 – 2009-12-25 10:34:08

+0

這真的很煩人。我實現了其他散列函數,將結構編碼爲字符串,並使用散列來散列這些散列函數。那些哈希函數正常工作,如果哈希工作不正確,爲什麼其他工作正常? – 2009-12-25 17:31:34