返回向量的单个索引值

时间:2019-12-13 03:36:29

标签: c++ arrays vector hash

我的任务是对向量进行哈希处理,并返回向量中每个元素的哈希索引值。我的代码为每个元素都返回了相同的值,但是我觉得我只需要四处移动即可解决问题。我到目前为止所拥有的:

void HashNames::hash(string fileName)
{
    ifstream infile(fileName);
    string tmp;
    for (int i = 0; i < 1002; i++)
    {
        infile >> tmp;
        this->nameList.push_back(tmp);
        for (int i = 0; i < nameList.size(); i++)
        {
            this->index = djbHash(tmp, 53);
        }
    }
}
int HashNames::djbHash(string data, int table)
{
    int hashVal = 5381;
    for (int i = 0; i < data.length(); i++)
    {
        hashVal *= 33;
        hashVal += static_cast<int>(data[i]);
    }
    hashVal %= table;
    return abs(hashVal);
}
void HashNames::printNames()
{
    for (int i = 0; i < this->nameList.size(); i++)
    {
        cout << this->index << ": " << this->nameList[i] << endl;
    }
}

该类的样子:

class HashNames
{
private:
    int index;
    vector<string> nameList;
    int djbHash(string data, int table);
public:
    void hash(string fileName);
    void printNames();
};

1 个答案:

答案 0 :(得分:0)

想想我自己弄清楚了,我又做了一个int向量,做了:

        for (int i = 0; i < nameList.size(); i++)
        {
            this->index = djbHash(tmp, 53);
            this->hashTable.push_back(index);
        }