繁体   English   中英

为什么这会给出运行时浮点错误?

[英]Why does this gives a runtime floating point error?

我正在为学校引入哈希表的作业,因此我正在为使用std::hash函数的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:我也尝试用硬编码5(这是this->size应该评估为this->size()替换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(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM