簡體   English   中英

在std :: pair中存儲std :: string和自定義對象

[英]Storing std::string and custom object in std::pair

我正在編程自己的哈希表實現。 對於這個項目,我有一個std::list數組,這是我存儲數據的表。 每個列表由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;
            }
        }
    }
}

您存儲一個指向對象引用的指針。 但是當您離開第一個函數時,該對象將被取消引用,因此您的表指向未初始化的內存。 我建議不要使用指針存儲數據,而應使用emplace方法來避免進行復制。

std::list<std::pair<std::string, StudentRecord*>*>不擁有指向的對象,而僅擁有指針。

您必須進行復制,可以通過將類型更改為以下內容來實施此操作:

std::list<std::pair<std::string, StudentRecord*>>

您還必須調整您的m_Table類型,從您的示例中我看不到它是什么。

如果要保留指針,則需要更改

std::pair<std::string, StudentRecord*> ptr = { p_Name, p_StudentRecord };

在堆而不是堆棧上分配對象。 (即使用new

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM