1

I would like to put use a string* as a key in an unordered_list. I do not want the hash the pointer itself but the string it points to.

I understand I need to create a struct like this:

struct myhash{
    size_t operator()(const string * str){
        return hash(*str);
    }
}

and send it as a a hasher to the map template, but i am not sure how.

izex
  • 123
  • 1
  • 10
  • 3
    Is there a reason you must use a `string*` and not a `string`? If you use a `string`, then the `unordered_list` will correctly handle the `string`'s lifetime. If you use a `string*`, then you will have to handle the lifetime. Make sure you really get something out of accepting that task (lifetime management). – Max Lybbert Jul 26 '10 at 08:55
  • If you found your question answered, click the check. :) Also, take into consideration what `Max` said: you have to manage those lifetimes manually, which is bad. (So this is okay as long as the pointers are non-owning.) If they are owning, use `shared_ptr` or `unique_ptr`. – GManNickG Jul 26 '10 at 09:01

1 Answers1

2

That's basically it. You then provide it as the third template parameter to the unordered_map type (Which I will assume to be the C++0x one). I would generalize it so it's usable in any situation, rather than just string:

struct dereference_hash
{
    template <typename T>
    std::size_t operator()(const T* pX)
    {
        return std::hash<T>()(*pX);
    }
};

typedef std::unordered_map<std::string*, int, dereference_hash> map_type;
GManNickG
  • 494,350
  • 52
  • 494
  • 543