我正在为学校引入哈希表的作业,因此我正在为使用该std::hash
函数的哈希表创建模板化的类。我遇到的问题出现在我的insert
函数中,如下所示:
template <class K, class V>
void HashMap<K, V>::insert(K key, V value)
{
std::hash<std::string> stringHash;
int intKey = stringHash(key);
int bucket = intKey % this->size();
map[bucket].push_back(std::pair<K, V>(key, value));
}
我的错误发生在以下行:int bucket = intKey % this->size();
。
我不太明白为什么这会产生浮点错误,因为我的工作完全是整数。使用键“ banana”和值3,散列的int为2068534322。在this->size
为5的情况下,模的取值为2。
那么,为什么我会出现浮点错误呢?
编辑1:我也尝试this->size()
用硬编码5(这是this->size
应该评估为)代替,所以this->size
用0评估没有问题。
您执行模(==除法)运算,因此需要确保分母不为零
template <class K, class V>
void HashMap<K, V>::insert(K key, V value)
{
std::hash<std::string> stringHash;
int intKey = stringHash(key);
int bucket = this->size() ? intKey % this->size() : intKey;
// or whatever makes sense to assign for the latter condition
map[bucket].push_back(std::pair<K, V>(key, value));
}
或者至少assert
在执行此操作时放置一条语句以跟踪错误的呼叫来源:
std::assert(this->size());
int bucket = intKey % this->size();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句