hash_map give unexpected value.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • eagerlearner
    New Member
    • Jul 2007
    • 29

    hash_map give unexpected value.

    Can anyone check this out, why does this give me the default value of 0 instead of 1 ? Thank you.
    Code:
    #include <iostream>
    #include <hash_map>
    #include <string>
    using namespace std;
    
    int main()
    {
    	stdext::hash_map<const char *, int> hm;
    	hm["abc"] = 1;
    	hm["def"] = 2;
    
    	string s = "abc";
    
    	cout << hm[s.c_str()];
    
    	return 0;
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by eagerlearner
    Can anyone check this out, why does this give me the default value of 0 instead of 1 ? Thank you.
    Code:
    #include <iostream>
    #include <hash_map>
    #include <string>
    using namespace std;
    
    int main()
    {
    	stdext::hash_map<const char *, int> hm;
    	hm["abc"] = 1;
    	hm["def"] = 2;
    
    	string s = "abc";
    
    	cout << hm[s.c_str()];
    
    	return 0;
    }
    If you don't supply a map with a comparator, the default < (less) will be used.
    Comparing (character) pointers using the < operator doesn't work so you have
    to supply the map an explicit comparator:

    [code=cpp]
    struct comp {
    bool operator() (const char* lhs, const char* rhs) const {

    return strcmp(lhs, rhs);
    }
    };

    int main() {
    map<const char *, int, comp> hm;
    ...
    [/code]

    I used an ordinary map instead of your hash_map, but I don't think it matters.
    (the hash_map is not in my version of the STL).

    kind regards,

    Jos

    Comment

    • eagerlearner
      New Member
      • Jul 2007
      • 29

      #3
      Thanks for the reply, I just found out that for hash_map it has to derive the class from hash_compare and at least both the hash function and comparison must be specified. Thank you.

      Code:
      class hasher : public stdext::hash_compare<const char *>
      {
      public:
      
      size_t operator() (const char* s) const
      {
      	size_t h = 0;
      	size_t max, i;
      	for(i = 0, max = strlen(s); i < max; i++)
      	{
      	  h = 31 * h + s[i];
      	}
      	return h;
      }
      	bool operator() (const char* lhs, const char* rhs) const
      	{
      		return (strcmp(lhs, rhs) < 0);
      	}
      };
      
      static stdext::hash_map<const char *, int, hasher> hm;

      Comment

      Working...