Question

I've tried to translate djb2 hash function from c-code

unsigned long
hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

to c++ code, but i have segmentation fault.

int hf(std::string s){
    unsigned long hash = 5381;
    char c;
    for(int i=0; i<s.size(); i++){
        c=s[i++];
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }
    return hash;

Where is my mistake? Thanks in advance

Was it helpful?

Solution

You want s[i], not s[i++]. Even better would be to use range-based for.

int hf(std::string const& s) {
    unsigned long hash = 5381;
    for (auto c : s) {
        hash = (hash << 5) + hash + c; /* hash * 33 + c */
    }
    return hash;
}

OTHER TIPS

Here's one I made that is pretty fast and c++ friendly.

unsigned long DJB2hash(string str)
{
    unsigned long hash = 5381;
    unsigned int size  = str.length();
    unsigned int i     = 0;
    for (i = 0; i < size; i++) {

        hash = ((hash << 5) + hash) + (str[i]); /* hash * 33 + c */
    }

    return hash;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top