How can I hash a string to an int using c++?

前端 未结 10 1812
长发绾君心
长发绾君心 2020-12-29 07:27

I have to write my own hash function. If I wanted to just make the simple hash function that maps each letter in the string to a numerical value (i.e. a=1, b=2, c=3, ...), i

10条回答
  •  时光取名叫无心
    2020-12-29 08:14

    Re the first question, sure, e.g, something like:

    int hash = 0;
    int offset = 'a' - 1;
    for(string::const_iterator it=s.begin(); it!=s.end(); ++it) {
      hash = hash << 1 | (*it - offset);
    }
    

    regarding the second, there are many better ways to hash strings. E.g., see here for a few C examples (easily translatable to C++ along the lines of the snippet above).

提交回复
热议问题