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;
}