什么可以修复这个哈希函数抛出的 for-loop 错误?
What can fix the for-loop error this hash function is throwing?
我正在制作乘法字符串哈希函数,但我的 for 循环抛出错误。我试图通过使用字符串值的长度来遍历字符串值中的每个字符。
错误:
hashtable.cpp:29:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::__cxx11::basic_string<char>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare] for (int i = 0; i < key.length(); i++)
哈希函数:
int HashTable::Hash(string key)
{
int hash = 5381; //initial value
for (int i = 0; i < key.length(); i++) //line that is causing error
{
hash = (hash * 33) + (int)key[i];
}
return hash % size;
}
是否有其他方法来编写我的条件语句来避免此错误?
length()
returns size_t
是无符号的。混合有符号 (i
) 和无符号 (key.length()
) 是有问题的,所以这就是错误所在。
您可以:
- 使用
std::size_t i
- 使用
static_cast<int>(key.length())
- 最好使用范围
for (auto ch : key)
我正在制作乘法字符串哈希函数,但我的 for 循环抛出错误。我试图通过使用字符串值的长度来遍历字符串值中的每个字符。
错误:
hashtable.cpp:29:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::__cxx11::basic_string<char>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare] for (int i = 0; i < key.length(); i++)
哈希函数:
int HashTable::Hash(string key)
{
int hash = 5381; //initial value
for (int i = 0; i < key.length(); i++) //line that is causing error
{
hash = (hash * 33) + (int)key[i];
}
return hash % size;
}
是否有其他方法来编写我的条件语句来避免此错误?
length()
returns size_t
是无符号的。混合有符号 (i
) 和无符号 (key.length()
) 是有问题的,所以这就是错误所在。
您可以:
- 使用
std::size_t i
- 使用
static_cast<int>(key.length())
- 最好使用范围
for (auto ch : key)