0

我一直在为我的一门课做一个非常深入的项目。它应该读入 Person 对象并将它们放入哈希表中。我仍在尝试了解哈希表的概念,因此将不胜感激。它将基于姓氏进行散列,并且由于某些人可能具有相同的姓氏,因此我打算将每个存储桶设为 Person 对象的向量。我正在尝试通过将一个人添加到散列函数然后返回它来测试该类。我的代码编译成功,但在这一行的 put 函数中出现线程错误:table[index].push_back(p);

谁能帮我弄清楚出了什么问题?谢谢!

int main()
{
    HashTable ht(10);
    ht.put(p1, p1->lName);
    ht.getName("Booras");
}


HashTable:
#include "Person.h"
#include <vector>

class HashTable: public DataStructures
{
private:
    vector<vector<Person>> table;
public:
    HashTable(int tableSize);
    ~HashTable();
    int tableSize;
    void getName(string str); //prints out friends with matching name
    void put(Person p, string str);
    void remove(Person *p, string str);
    int hash(string str);

};
HashTable::HashTable(int tableSize)
{
    vector< vector<Person> > table(tableSize, vector<Person>(tableSize));
    for (int i = 0; i < tableSize; i++) {
        table.push_back(vector<Person>()); // Add an empty row
    }
}

HashTable::~HashTable()
{

}

//Find a person with the given last name
void HashTable::getName(string key)
{
    int index = hash(key);
    for(int i=0; i<table[index].size(); i++)
    {
        if(table[index][i].lName.compare(key) == 0)
            std::cout << "Bucket: " << index << "Bin: " << i;
            table[index][i].print();
    }
    //create exception for person not found
}

void HashTable::put(Person p, string str)
{
    int index = hash(str);
    table[index].push_back(p);
}

void HashTable::remove(Person *p, string str)
{
    int index = hash(str);
    int i=0;
    while(&table[index][i] != p && i<table[index].size())
        i++;
    for(int j=i; j<table[index].size()-1; j++)
        table[index][j] = table[index][j+1];
    table[index].pop_back();
}

int HashTable::hash(string str)
{
    int hashValue = 0;
    for(int i=0; i<str.length(); i++)
    {
        hashValue = hashValue + int(str[i]);
    }
    hashValue %= tableSize;
    if(hashValue<0) hashValue += tableSize;
    return hashValue;
}

主要的:

int main() {
    Person *p1 = new Person("Kristy", "Booras", "Reston", "03/15");
    HashTable ht(10);
    ht.put(*p1, p1->lName);
    ht.get("Booras");
return 0;
}
4

1 回答 1

0

您没有向我们展示HashTable::hash(string)成员函数,但我假设您的问题源于HashTable构造函数:您没有初始化tableSize成员变量,您需要计算有效的散列索引。

在查看构造函数时:

HashTable::HashTable(int tableSize)
{
    vector< vector<Person> > table(tableSize, vector<Person>(tableSize));

这已初始化table为具有tableSize非空元素,总共tableSize * tableSize默认构造的Person对象。

    for (int i = 0; i < tableSize; i++) {
        table.push_back(vector<Person>()); // Add an empty row
    }
}

现在您已经添加了更多行,因此,table.size() == 2*tableSize前半部分条目非空(如上所述),后半部分包含空向量。

这可能不是你想要的。

在所有这些中,您还没有初始化 member tableSize。如果您使用隐藏成员名称的局部变量或参数名称,它很容易混淆。

于 2013-02-15T16:57:58.407 回答