Vijay
Vijay

Reputation: 67221

Can any one tell what is the 4th line in this function doing!

size_t hash(const std::string data) {
    size_t h(0);
    for (int i=0; i<data.length(); i++){
        h = (h << (31-i) ^ (h >> i) ^ data[i]);
    }
    h = h%hashsize;
    return h;
}

Upvotes: 1

Views: 102

Answers (1)

ildjarn
ildjarn

Reputation: 62975

It's a hash function for std::string, ostensibly suitable for TR1 and C++11's std::unordered_map<>, std::unordered_set<>, etc. I.e., it attempts to create an as-unique-as-possible size_t value for the given std::string for use in hash tables.

That being said, it's a poor hash function. Any standard library implementation that comes with unordered_map<>, unordered_set<>, etc. will come with built-in hash functions for standard library strings that have better implementations than this one.

EDIT: (In response to comment) << is bitwise shift left, >> is bitwise shift right, and ^ is bitwise XOR, all of which are briefly discussed in this wikipedia entry: Bitwise operation.

Upvotes: 3

Related Questions