[英]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.