简体   繁体   中英

Why does this gives a runtime floating point error?

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.

You do a modulo (== division) operation, so you need to assure your denominator isn't zero

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

Or at least place an assert statement when doing this to track where wrong calls came from:

std::assert(this->size());
int bucket = intKey % this->size(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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