我的任务是对向量进行哈希处理,并返回向量中每个元素的哈希索引值。我的代码为每个元素都返回了相同的值,但是我觉得我只需要四处移动即可解决问题。我到目前为止所拥有的:
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();
};
想想我自己明白了,我又做了一个int向量并且做了:
for (int i = 0; i < nameList.size(); i++)
{
this->index = djbHash(tmp, 53);
this->hashTable.push_back(index);
}