我想在unordered_list中使用字符串*作为键。我不希望哈希指针本身,但它指向的字符串。在unordered_set中使用字符串*作为键
我明白,我需要建立一个结构是这样的:
struct myhash{
size_t operator()(const string * str){
return hash(*str);
}
}
,并把它作为一个散列器到地图模板,但我不知道怎么样。
我想在unordered_list中使用字符串*作为键。我不希望哈希指针本身,但它指向的字符串。在unordered_set中使用字符串*作为键
我明白,我需要建立一个结构是这样的:
struct myhash{
size_t operator()(const string * str){
return hash(*str);
}
}
,并把它作为一个散列器到地图模板,但我不知道怎么样。
基本上就是这样。然后,您将其作为第三个模板参数提供给unordered_map
类型(我将假定它是C++ 0x之一)。所以它的使用在任何情况下,而不是仅仅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;
是否有您必须使用'字符串*'而不是'string'理由吗?如果使用'string',那么'unordered_list'将正确处理'string'的生命周期。如果你使用'string *',那么你将不得不处理一生。确保你真的从接受任务中获得了一些东西(终身管理)。 – 2010-07-26 08:55:51
如果您发现问题得到解答,请点击支票。 :)另外,考虑一下'Max'说:你必须手动管理这些生命周期,这是不好的。 (所以只要指针是非拥有的就可以。)如果它们拥有,则使用'shared_ptr'或'unique_ptr'。 – GManNickG 2010-07-26 09:01:17