2

I am doing an assignment for school which introduced hashmaps, and so I am creating a templated class for a hashmap that uses the std::hash function. The problem that I am having comes in my insert function, which is shown below:

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

My error occurs at the line: int bucket = intKey % this->size();.

I don't quite understand why this would give a floating point error since I am doing my work entirely in integers. With the key "banana" and the value 3, the hashed int is 2068534322. In the case where this->size is 5, the modulo should be evaluated as 2.

So, why exactly am I getting a floating point error?

EDIT 1: I also tried this->size() replaced with a hard-coded 5 (which is what this->size should evaluate to), so the this->size isn't having a problem evaluating with a 0.

4

1 回答 1

4

你做一个模(==除法)运算,所以你需要确保你的分母不为零

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(); 
于 2014-06-02T20:18:24.550 回答