srand producing same random number every function call

I'm writing a program to create a hash table but the hash function keeps giving me back the same number no matter how i write it making every insert in the same bucket and extending the linked list. I can add more code if it helps but this is where i feel the error is.

Hash Function:
1
2
3
4
5
6
7
8
int HashTable::hash(std::string key)
{
    int hashValue;
    srand (time(0));
    hashValue = rand() % (size - 1) + 0;
    std::cout << key << std::endl;
    std::cout << "HashValue" << hashValue << std::endl;
    return (hashValue);
Last edited on
Line 4: Every time you call your hash function, you're resetting the starting point of the RNG. srand should be called ONCE at the beginning of main. Do not call it repeatedly.
http://www.cplusplus.com/reference/cstdlib/srand/
Maybe try to put int size as a parameter
OP: don't change the post header to 'SOLVED", instead check the green box. SOLVED means nothing for anyone scrolling through posts looking for info

edit: OP - thanks for reverting back to the original ('ish)
Last edited on
BTW, why not just use std::hash<std::string>()(key)? for eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# include <iostream>
# include <string>
# include <functional>
# include <vector>

int main()
{
    std::vector<std::string> data{ {"how"}, {"are you?"}, {"happy"}, {"new year"}, {"long"}, {"live the revolution"},
                                    {"dog"}, {"ate my homework"}};

    for (const auto& elem : data)
    {
        std::cout << std::hash<std::string>()(elem) << " ";
    }
}

http://en.cppreference.com/w/cpp/utility/hash
It's for a data structure class so we have to write each function for the hashtable but that is definitely a more efficient way of doing it. Thanks for the help though! And i thought the title was a better depiction of the content so i changed it from solved lol.
Topic archived. No new replies allowed.