Search code examples
c++stringfor-loophashtable

What can fix the for-loop error this hash function is throwing?


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?


Solution

  • 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:

    • use std::size_t i
    • use static_cast<int>(key.length())
    • better yet use range for for (auto ch : key)