返回向量的单个索引值

Returning individual index values of a vector

本文关键字:索引值 单个 向量 返回      更新时间:2023-10-16

我的任务是散列向量并返回向量中每个元素的散列索引值。但是,我的代码为每个元素返回相同的值,但我觉得我只需要移动一些东西来解决问题。到目前为止,我拥有的:

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();
};

我想我自己想通了,我只是做了另一个整数向量并做到了:

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