tags:

views:

83

answers:

2

I have to create a lookup table for C function names (as keys) to function pointers (as values). I am thinking of using STL's hash_map container, as the access time of a hash table is O(1). Is there any good hash function for this? Currently I am using (31*H + c) as my hash function.

Also, does STL's hash_map takes care of collisions, or I have to take care of them in my code? Please give some examples if possible.

Sample Code I am currently working upon

#include <iostream>
#include <ext/hash_map>;

using namespace std;
using namespace __gnu_cxx;

namespace __gnu_cxx {
#ifndef __HASH_STRING__
#define __HASH_STRING__
  template <>
    struct hash<string> {
      size_t operator() (const std::string& s) const
      {
        size_t h = 0;
        std::string::const_iterator p, p_end;
        for(p = s.begin(), p_end = s.end(); p != p_end; ++p)
        {
          h = 31 * h + (*p);
        }
        return h;
      }
    };
#endif
};

int main()
{
  hash_map<string, int> months;

  months["january"] = 1;
  months["february"] = 2;
  months["march"] = 3;
  months["april"] = 4;
  months["may"] = 5;
  months["june"] = 6;
  months["july"] = 7;
  months["august"] = 8;
  months["september"] = 9;
  months["october"] = 10;
  months["november"] = 11;
  months["december"] = 12;

  return 0;
}
A: 

You don't need to deal with collisions. Also, I think std::hash is already defined, so you don't need to worry about a hash function.

Neil G
A: 

Assuming you've got the full STL, it actually includes a hash function, hash<T>, which in its included form is suitable for a few different key types including char* (C strings). I don't know details of its performance, but the STL is generally engineered to have acceptable performance for most applications.

As for collisions, that's for hash_map to deal with, you needn't worry about it.

Nicholas Knight
what do you mean by full STL? How I am going to check whether I got full STL or not? I have also added the sample code I am currently writing.
Ravi Gupta
@Ravi: The STL is not part of the actual C++ standard (though a subset of it was incorporated into the C++ standard library). Bits of it have shown up with compilers from time to time, but often incomplete, sometimes in surprising ways. Since you seem to be working with GCC/g++, though, I can safely say you should have have `hash<T>`.
Nicholas Knight
To clarify, C++ has a standard library. Saying "the STL" to mean "the standard library" is a misnomer. It could mean the standard library, the template parts of the standard library, the original STL, or something else. Ravi probably meant "the standard library", while I think Nicholas means "the SGI STL."
GMan
@GMan: I know STL is Standard Template Library which is a subset of standard C++ library.
Ravi Gupta
@Ravi: That might be 'a' definition, but not 'the' definition. C++ does not define "STL" or "Standard Template Library".
GMan
Ravi Gupta
Billy ONeal