【问题标题】:Effeciently Searching a Hash Table without using the Key在不使用密钥的情况下有效地搜索哈希表
【发布时间】:2013-11-18 05:35:17
【问题描述】:

我有一个包含歌曲列表的哈希表。通过将歌曲的标题翻译成它的 ascii 字符并使用这个数字 [% table size] 作为键,每个歌曲节点都被插入到表中。每个歌曲节点中还有一个“艺术家”字段。如果我想显示特定艺术家的每首歌曲,我可以在不搜索整个表中的每个节点的情况下这样做吗?我在下面包含了我的插入和散列方法。顺便说一句,散列函数的合适名称是什么?

头文件:

struct song {
    string title;
    string artist;
    song* next;
};

class hash {
public:
    hash();
    int Hash_Key(string key); // For determining the hash key for a string
    // Do I need to use multiple hash functions or multiple strings?
    int Add_Item(string title, string artist); // for adding song to hash table
private:
    static const int tableSize = 7;
    song* HashTable[tableSize];
};

实施:

int hash::Add_Item(string title, string artist) {
    int index = Hash_Key(name);
    if(HashTable[index]->title == "empty") { // if first item at this index
        HashTable[i]->title = title;
        HashTable[i]->artist = artist;
    }
    else { // if not the first item at this index
        song* temp = HashTable[index];
        song* n = new song;
        n->title = title;
        n->artist = artist;
        n->next = NULL;
        while(temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = n;
    }


    return 0; // temporary
};

int hash::Hash_Key(string key) {
    int hash = 0;

    for(int i = 0; i < key.length(); i++) {
        hash = hash + (int)key[i];
    }

    index = hash % tableSize; // remainder of the sum of ascii values of key
                              // divided by tableSize
    return index;
}

【问题讨论】:

标签: c++ search hashtable


【解决方案1】:

最好创建一个“艺术家 -> 歌曲*”的新地图,并在添加/删除项目时保持两个地图都是最新的。

【讨论】:

  • 那么像第二个哈希表,但使用艺术家作为键?
猜你喜欢
  • 2020-03-29
  • 2020-12-09
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
相关资源
最近更新 更多