I'm trying to use a functor with definable state as the hasher for an unordered_set, the problem i'm faced with is I doesn't know how to initialize the functor passed as the template parameter. It would be something like this.
class A{
private:
class Hasher{
private:
int a;
public:
Hasher(int val=3):a(val){};
size_t operator()(const string & s) const{
return s[0]*a;
}
};
unordered_set<string,Hasher??> us;
int hasher_val;
public:
A(int h_val):hasher_val(h_val){};
}
The problem is, how can I define "a" for a value different to 3?
std::unordered_set
's constructor has optional parameters which can be used to initialize its hash instance:
unordered_set<string,Hasher> us;
int hasher_val;
public:
A(int h_val) : us{51, Hasher(4)}, hasher_val{h_val}{};
One slightly uncomfortable fact is that the hash instance is the second parameter, and you have to explicitly specify your hash bucket size, instead of relying on the wisdom of your C++ library to provide a suitable default (in my example, I just picked 51 off the top of my head, which is probably very, very wrong but that would be a different question to mull over...).
You should spend a few minutes digging into your header files to determine what default your C++ implementation uses, for the set's bucket size, and supply the same value.
P.S. The same approach is used with all library containers: their constructors' parameters are all defaulted, making it possible to explicitly construct them using a custom hash class instance, a custom comparator class instance, etc...