code_junkie

What's the best hashing algorithm to use on a stl string when using hash_map?

Nov 11th, 2011
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. /* magic numbers from http://www.isthe.com/chongo/tech/comp/fnv/ */
  2. static const size_t InitialFNV = 2166136261U;
  3. static const size_t FNVMultiple = 16777619;
  4.  
  5. /* Fowler / Noll / Vo (FNV) Hash */
  6. size_t myhash(const string &s)
  7. {
  8. size_t hash = InitialFNV;
  9. for(size_t i = 0; i < s.length(); i++)
  10. {
  11. hash = hash ^ (s[i]); /* xor the low 8 bits */
  12. hash = hash * FNVMultiple; /* multiply by the magic number */
  13. }
  14. return hash;
  15. }
  16.  
  17. unsigned int
  18. hash(
  19. const char* s,
  20. unsigned int seed = 0)
  21. {
  22. unsigned hash = seed;
  23. while (*s)
  24. {
  25. hash = hash * 101 + *s++;
  26. }
  27. return hash;
  28. }
  29.  
  30. template <> struct myhash{};
  31.  
  32. template <> struct myhash<string>
  33. {
  34. size_t operator()(string &to_hash) const
  35. {
  36. const char * in = to_hash.c_str();
  37. size_t out=0;
  38. while(NULL != *in)
  39. {
  40. out*= 53; //just a prime number
  41. out+= *in;
  42. ++in;
  43. }
  44. return out;
  45. }
  46. };
  47.  
  48. hash_map<string, int, myhash<string> > my_hash_map;
Add Comment
Please, Sign In to add comment