我正在编写自己的散列表实现。对于这个项目,我有一个数组std::list
,这是我存储数据的表格。每个列表由std::pair
对象组成。一对包含std::string
(人的姓名)和一个指向自定义类(包含关于该人的数据的类)的对象的指针。在std :: pair中存储std :: string和自定义对象
我有一个执行put()方法在散列表中插入数据的问题。这是我写的代码。
pair<string,StudentRecord*>* HashTable::put(string& p_Name, StudentRecord* p_StudentRecord){
std::pair<std::string, StudentRecord*> ptr = { p_Name, p_StudentRecord };
this->put(&ptr);
return &ptr;
}
void HashTable::put(pair<string, StudentRecord*>* p_HTElement){
string key = p_HTElement->first;
int storage_place = this->m_Hasher->hash(key) % this->m_Capacity;
this->m_Table[storage_place].push_back(p_HTElement);
this->m_NumberOfEntries++;
this->updateLoadFactor();
if (this->m_LoadFactor >= MAX_LOAD_FACTOR)
this->rehash();
}
当需要添加数据时,将调用第一个方法。此方法创建一个std::pair
对象并将此对象的引用传递给第二个方法。第二种方法然后计算散列并将其放入std :: list数组中。然而,问题在于,将它放入数组后std::string
(该对的第一个元素)不再可读。当我看着调试器时,它只是说它的值是“”。在后面的阶段中,我想查找散列表中的数据,我的方法printHashTable()确实认识到它们是列表中的一对,但它不能读取数据。再次与调试器,它说串
的
错误读数字符的对的第一元件和用于自定义对象,它说
0xccccccccc
这是我的方法,该方法需要打印散列表中的所有数据:
void HashTable::printTable(){ for (int i = 0; i < this->m_Capacity; i++){ if (!this->m_Table[i].empty()) { for (std::list<std::pair<std::string, StudentRecord*>*>::iterator element = this->m_Table[i].begin(); element != this->m_Table[i].end(); ++element) { cout << (*element)->first << endl; } } } }
你的成员变量的类型是什么? – tillaert
返回指向局部变量的指针... –
自定义类StudentRecord的成员变量?学生记录仅包含std :: string和int变量。 @MarcGlisse我明白了。但是,如果我需要创建一个新的对象,并且它不能在方法put()中创建,那么我该怎么做呢? –