Reputation: 17
I am making a multiplicative string hash function and my for-loop is throwing an error. I am attempting to iterate through each character in the string value by using its length.
The error:
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++)
Hash function:
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;
}
Is there another way to write my condition statement to avoid this error?
Upvotes: 0
Views: 117
Reputation: 75874
length()
returns size_t
which is unsigned. Mixing signed (i
) with unsigned (key.length()
) is problematic so this is what the error is about.
You can:
std::size_t i
static_cast<int>(key.length())
for (auto ch : key)
Upvotes: 2