首页 > 解决方案 > 打印 C++ 哈希表的问题

问题描述

我对 C++ 很陌生,正在尝试自学如何实现哈希表(我知道我可以使用 unordered_map,但我正在挑战自己)。现在我有一个包含个人特定信息的 structs(cell) 向量。我有一个 PrintTable 函数,我想用它来打印表中每个项目的每个结构成员。但是,我似乎无法访问 struct(cell) 的特定成员。我在这里做错了什么?

#include <iostream>
#include <string>
#include <vector>

struct cell
{
    std::string name;
    int age;
    std::string weapon;
};

class HashTable
{
private:
    std::vector<cell> *table;
    int total_elements;

    int getHash(int key)
    {
        return key % total_elements;
    }

public:
    HashTable(int n)
    {
        total_elements = n;
        table = new std::vector<cell>[total_elements];
    }

    void SearchTheTable(int hashIndex);
    void AddItem(std::string name, int age, std::string weapon);
    void RemoveItem();
    void PrintTable();
};

void HashTable::SearchTheTable(int hashIndex)
{
    int x = getHash(hashIndex);
    std::cout << x;
}

void HashTable::AddItem(std::string name, int age, std::string weapon)
{
    cell newCell = { name, age, weapon };
    table->push_back(newCell);
}

void HashTable::RemoveItem()
{

}

void HashTable::PrintTable()
{
    for (int i = 0; i < table->size; i++)
    {
        std::cout << table[i].name; // Right here I get an error that says: class "std::vector<cell, std::allocator<cell>>" has no member "name".
    }
}

int main()
{
    HashTable theTable(5);
    theTable.AddItem("Ryan", 27, "Sword");
    theTable.AddItem("Melony", 24, "Axe");
    theTable.PrintTable();
}

标签: c++

解决方案


推荐阅读