int main()
{
hash_map<const char*, int, hash<const char*>, eqStr> Map;
return 0;
}
The compiler complaints ‘hash’ is undeclared. Is the hash function
declared in Dinkum libraries?
kc:
I, too, have an interest in this matter, so your question motivated me to
once again try to find the answers. The short answer to your question is:
No, Dinkum does not seem to supply a hash function for ‘const char*’ (or
string). I refer you to the Dinkum manpages, and the header files
<cpp/hash_map> and <cpp/xhash>.
The Dinkum hash_map uses hash_compare<Key, less> as a “hash traits”
function object. It includes (among other things) the hashing function
‘size_t operator()(const Key& key)’, which by default returns key
(implicitly casting it to size_t).
So, if you try this,
hash_map<const char*, int> Map;
it will compile. However, if you then try an insertion,
Map[“0”] = 0;
it will not compile because the hash function returns ‘const char*’ as a
size_t without a cast. (Note that the Dinkum hash_map has a different
parameter signature than you are using–i.e., its fourth parameter is an
allocator, not an equality functor.)
As a first attempt, I got something like this to compile and run with the
Dinkum library:
#include <hash_map>
#include
using namespace std;
typedef const char* CSTRING;
class cstringhash : public hash_compare< CSTRING >
{
public:
cstringhash();
size_t operator()(CSTRING key) const;
bool operator()(CSTRING const& key1, CSTRING const& key2) const;
};
inline cstringhash::cstringhash()
: hash_compare< CSTRING >()
{
}
inline size_t
cstringhash::operator()(CSTRING key) const
{
return (size_t)key;
}
inline bool
cstringhash::operator()(CSTRING const& key1, CSTRING const& key2) const
{
return hash_compare< CSTRING >::operator()(key1, key2);
}
int main()
{
hash_map<const char*, int, cstringhash> m;
m[“0”] = 0;
m[“99”] = 99;
cout << m[“0”] << endl;
cout << m[“99”] << endl;
return 0;
}
Of course, my hash function compiles and runs, but it is useless. I do not
know (or care) about hashing functions–I would just like to be able to use
the darn thing with a string index without all this hassle (Perl has spoiled
me)–but Stroustrup (The C++ Programming Language, 3rd edition, p. 503)
provides one which I adapt here:
inline size_t
cstringhash::operator()(CSTRING key) const
{
size_t res = 0;
while(*key) res = (res << 1) ^ *key++;
return res;
}
This also compiles and runs. I assume that it has better than linear time
lookups, unlike my first implementation.
This completes my investigation, for now.
->>>–Sherwood–>