【发布时间】:2020-04-28 10:18:02
【问题描述】:
我正在尝试用 C++ 实现字典,但是当我定义类哈希的特化时,我得到了错误:
error: 'hash' is not a class template
error: template argument required for 'class hash'
这里是代码
template <class T>
class hash{
public:
size_t operator()(const T the_key) const;
};
/* a specialization with type string */
template<>
class hash<string>
{
public:
size_t operator()(const string the_key) const {
unsigned long hash_value = 0;
int length = (int) the_key.length();
for (int i=0; i<length; i++)
hash_value = 5 * hash_value + the_key.at(i);
return size_t(hash_value);
}
};
可能是什么问题?
【问题讨论】:
-
显示的代码没有明显的原因导致您报告的错误消息。请参阅this example,它编译得很好。问题可能在于您使用
hash的方式或位置。 -
注意:
const string the_key应该是const string & the_key以避免制作不必要的副本,您可能只使用size_t代替hash_value、length和i以避免任何类型的演员表.
标签: c++ dictionary data-structures hash hashtable