I'm trying to build a hash table class in C++ using the chaining method, a minimal example class is:
template <class V>
class HashTable {
private:
//some parameters to define the hash_table
HashFunc * h; //family of hash functions
public:
/*other functions*/
};
I'm having some troubles with the member HashFunc * h, which is the hash function I intend to use to store pairs <key,value> in the hash table. In my main, I need to build two different hash tables, one which hashes integers and another one which hashes strings.
My doubts are:
- A natural choice for me would be to use polymorphism for the hash function in the following way (mind that I have limited experience with classes and polymorphism):
class HashFunc{
public:
virtual int operator()()=0;
}
class IntegerHashFunc: public HashFunc
{
//parameters to hash integers
public:
int operator()(int x){
//operations for integer hashing
}
}
class StringHashFunc: public HashFunc
{
//parameters to hash strings
IntegerHashFunc h_integer; //string->integer->integer hash
public:
int operator()(string name){
int result=0;
//operations for string hashing
return h_integer(result); //I need to hash the integer resulting from string "hashing"
}
}
But this won't work because the operator()(string name) in StringHashFunc has different arguments and thus doesn't override the virtual method in the base class. How to make this work?
- I'm not sure on how to make this work in the constructor for the
HashTableclass: how to choose between the two methods? Should I just use a flag in the constructor like:
template<class V>
HashTable<V>::HashTable(/*args*/, int flag){
//other parameters
switch(flag){
case 1:
h=new IntegerHashFunc(/*args for integer hashing*/);
case 2:
h=new StringHashFunc(/*args for string hashing*/);
}
}
or is there a better way?
- Is there a better and more natural way to do what I want to do? For example, I tried using a single class
HashFuncwith two overloadsoperator()(int)andoperator()(string), but I don't want to "carry" around string parameters and methods if I'm working just with integers.