Re: unordered_map
On 7 Apr., 18:13, sje...@gmail.com wrote:
I am new to boost, and to templates (feeling very comfortable with C).
I am trying to use boost hash tables where the keys are char *, like:
unordered_map<const char *, CMyclass *> myclass_map_t ;
Note: I have no experience with this new facility of the
boost trunk, but it seems that it reflects the current
specification of upcoming C++0x std::unordered_map (given
current compiler technologies, i.e. modulo rvalue references
where not available).
1. Couldnt figure so far, how do i set a hash function that works on
the string (and not on the pointer) ?
IMO hash functions on string-like entities belong to
the most popular use-cases of hashers. A simple way would
be to have a look at boost's implementation for std::string,
which effectively calls boost::hash_range. So you could provide
something like
#include <string.h>
struct CharArrayHashEqual : std::unary_function<const char*,
std::size_t>
{
std::size_t operator()(const char* s) const {
return boost::hash_range(s, strlen(s));
}
bool operator(const char* s1, const char* s2) const {
return strcmp(s1, s2) == 0;
}
};
and use type CharArrayHash as the third (Hash) *and*
forth (EqualTo) template argument of boost::unordered_map.
Also very popular are the FVN algorithm,
http://www.isthe.com/chongo/tech/comp/fnv/
or the Jenkins hash,
http://burtleburtle.net/bob/hash/doobs.html
(instead of the "boost::hash_range(s, strlen(s))" part)
2. Whenever i get a new key i want to check first if it is already in
the hash table, if yes - get its value, and if not have the
opportunity to create a new value for it, but be able to do it with
one operation. Is there a way to achieve that ?
You will probably write a helper function which does
this, which e.g. uses the member function insert that
returns a pair<iterator, bool>. Depending on the bool
part of the return value you can modify the value
accessible via the iterator result value or not.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]