【问题标题】:Why does this gives a runtime floating point error?为什么这会产生运行时浮点错误?
【发布时间】:2014-07-23 00:49:36
【问题描述】:

我正在为介绍哈希图的学校做作业,因此我正在为使用 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-&gt;size();

我不太明白为什么这会产生浮点错误,因为我的工作完全是整数。使用键“banana”和值 3,散列后的 int 为 2068534322。在 this-&gt;size 为 5 的情况下,模数应计算为 2。

那么,我到底为什么会遇到浮点错误?

编辑 1:我还尝试将 this-&gt;size() 替换为硬编码的 5(这是 this-&gt;size 应该评估的值),所以 this-&gt;size 用 0 评估没有问题。

【问题讨论】:

  • 如果需要更多信息来帮助,请随时给我留言。我不想提供太多信息,以免让人不知所措。
  • K 是什么类型?你确定size不为零吗?
  • 什么是“浮点错误”?请详细描述您遇到的错误。
  • 您可能会在执行此操作时断言this-&gt;size(); 不是0
  • 这对您来说非常容易调试。不要无助。如果int bucket = intKey % this-&gt;size(); 行导致运行时错误,请使用调试工具确定传递给% 运算符的值。这真的再简单不过了。知道这些值后,请制作一个简单的 SSCCE 来说明问题。

标签: c++ hashmap modulus sigfpe


【解决方案1】:

您执行模(== 除)运算,因此您需要确保分母不为零

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(); 

【讨论】:

  • 如果size() 是底层数组的大小并且等于0,这意味着没有map 可以放入东西。 IOW 这并不像用不同的值替换 bucket 那样容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 2015-02-22
相关资源
最近更新 更多