Re: cstring hash
In article <ktp3k6$kel$1@usenet.stanford.edu>, musiphil@bawi.org
(Seungbeom Kim) wrote:
Aren't we talking about the raw pointer of type 'const char *'
for T in std::unordered_set<T> or for K or V in
std::unordered_map<K, V>?
We're talking about wanting to hash (const char *) so they can
be used as keys, yes.
It's a reasonable assumption that if you put allocated strings in
such a container, it will be quite hard to make exception-safe
for all cases.
Why? What is wrong with (for example):
void set( const char *key, int value ) {
auto len = strlen( str ) + 1;
auto p = make_unique<char>( len );
strcpy( p.get(), str );
g_vec.push_back( move(p) );
g_map[ vec.back().get() ] = value;
}
where g_vec is responsible for deleting the strings, and g_map for
the indexing.
Using a unique_ptr<const char *> as the key for the unordered map
might be simpler, but we'd still need a way to hash all the
characters of the string. std::hash<std::unique_ptr<const char *>>()
will not do that. Similarly if we had our own string class, we'd
need to write a hash function for that. If the standard library
provided cstr_hash as the original poster suggested, it would be
useful in these situations.
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]