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

前端 未结 10 1851
长发绾君心
长发绾君心 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:15

    #include 
    #include 
    #include 
    
    using namespace std;
    
    // a variation on dan bernstein's algorithm
    // [http://www.cse.yorku.ca/~oz/hash.html]
    template
    struct hash {
        hash() : acc(5381) { }
        template
        void operator()(Ch ch) { acc = ((acc << 5) + acc) ^ ch; }
        operator Int() const { return acc; }
        Int acc;
    };
    
    int main(int argc, char* argv[])
    {
        string s("Hellp, world");
        cout << hex << showbase
            << for_each(s.begin(), s.end(), hash()) << '\n';
        return 0;
    }
    

提交回复
热议问题