为什么这会产生运行时浮点错误?
题
我正在为学校做一项引入哈希图的作业,因此我正在为使用以下内容的哈希图创建一个模板类 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();
不隶属于 StackOverflow