なぜこれはランタイムフローティングポイントエラーを与えるのですか?
質問
ハッシュマップを導入した学校の代入を行っているので、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:this->size()
をハードコード5に置き換えました(これは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();
. 所属していません StackOverflow