0

I am creating a HashTable class via a template. Although, I can't seem to find a way to keep the template nature when dealing with strings or any numerical datatype (more-so just integers). This is the code that I have that works as long as HashKey is of type string.

template<typename HashKey>
size_t HashTable<HashKey>::myhash(const HashKey & x) const
{
    unsigned int hashVal = 0;
    for (unsigned int i = 0; i < x; i++)
    hashVal = (hashVal << 5) ^ x[i] ^ hashVal;
    return hashVal % hashTable.size();
};

Would there be any way to allow it to work using something like

unsigned int hashVal = 0;
hashVal = (hashVal << 5) ^ x ^ hashVal;
return hashVal % hashTable.size();

Any help here?

Andrew B
  • 9
  • 1
  • 1
  • 2
  • 2
    Consider using [`std::hash`](http://en.cppreference.com/w/cpp/utility/hash), you can provide specializations for your own types if necessary. Also unless this is an exercise there's always [`std::unordered_set`](http://en.cppreference.com/w/cpp/container/unordered_set) / [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map). – user657267 Oct 23 '14 at 04:57
  • I have to come up with the hash-function myself. Wouldn't that just make me use the pre-made one? – Andrew B Oct 23 '14 at 05:02
  • That depends on what you will be hashing, the library only specializes `std::hash` for fundamental types and some other library types like `string`s, if you are hashing your own types you'll be providing your own function anyway so I wouldn't consider it "cheating". – user657267 Oct 23 '14 at 05:05
  • I was given `hash hf; return hf(x) % hashTable.size();` originally. So I can't use that. Strings and integers are the major types that I'm worried about though, no user defined ones. – Andrew B Oct 23 '14 at 05:10
  • Clearly what you're trying to do isn't possible unless you overload operators for `std::string` in ways that would make so sense outside `myhash()`, so your simplified *shouldn't* be the complete body for `myhash()`. You *could* apply a wrapper type atop `myhash()` that provided appropriate operations for the set of `HashKey` types you're aiming to support - ugly idea. Or - a little better - you could use SFINAE/`enable_if` to have an overload of `myhash` for `HashKey`s with `.begin()` and `.end()` - iterating anything that can be iterated, bitshifting and xoring the iterated-over values. – Tony Delroy Oct 23 '14 at 05:10
  • Anyway, it's better to give `HashTable` an extra parameter for the hash function (then simple overloading or specialisation can handle your types), and keep hashing separate from the `% hashTable.size()` adjustment. Even if you don't want to use `unordered_map`, it's a good idea to follow the same overall design approach - will keep you on a sane path. – Tony Delroy Oct 23 '14 at 05:10

0 Answers0