Frage

I'm fairly new to C++. I tried implementing a really simple hash table, and then I wanted to see if my hashing algorithm put the element in the correct position. However, apparently the element wasn't even added to the array at all:

void add(string str, array<string, 2000> data) {
    int i = makeHash(str) % data.size();

    while (data[i++ % data.size()].compare("") != 0)
        continue;

    data[i % data.size()] = str;
    cout << "Added!"; // successfully prints, meaning str was added to data
}

int main() {

    array<string, 2000> data;
    string str = "The quick brown fox something something";
    add(str, data);

    for (int i = 0; i < data.size(); i++)
        if (data[i].compare(str) == 0)
            cout << i; // never prints... so str was never added to data?

    return 0;
}
War es hilfreich?

Lösung

You need to pass data variable as reference -

void add(string str, array<string, 2000> &data)

What you are doing here is pass by value, so as soon as your function ends, value of data is destroyed.

Andere Tipps

Try passing data by reference, i.e.

void add ( string str, array<string, 2000>& data ){...}

Passing by value will mean a copy of data will be passed into the function. Also, there's an off by one error. I'm sure you want to have:

data[(i-1) % data.size()] = str;

because i will still be incremented when you exit the while loop.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top