c++ - 用于存储类对象的 C++ 哈希表
问题描述
我已经看到大量用于字符串或 int 值的哈希表实现。但是,我需要有关如何将对象作为值存储在哈希表中的帮助。我创建了一个 Book 类,需要将其实例存储到哈希表中。我怎么做 ?下面是我使用单独的链接来避免冲突的哈希表实现。
...
#ifndef HASH_H_
#define HASH_H_
#include <string>
#include <iostream>
using namespace std;
class hashtable{
private:
static const int tablesize = 10;
struct book{
string name;
string author;
book* next;
};
book* HashTable[tablesize];
public:
hashtable();
int Hash(string key);
void Add(string key, string author);
int num(int index);
void PrintTable();
void PrintItems(int index);
};
#endif
hashtable::hashtable(){
for(int i=0; i<tablesize; i++){
HashTable[i] = new book;
HashTable[i]->name = "empty";
HashTable[i]->author = "empty";
HashTable[i]->next = NULL;
}
}
void hashtable::Add(string name, string author){
int index = Hash(name);
if (HashTable[index]->name == "empty"){
HashTable[index]->name = name;
HashTable[index]->author = author;
}else{
book* Ptr = HashTable[index];
book* n = new book;
n->name = name;
n->author = author;
n->next = NULL;
while (Ptr->next != NULL){
Ptr = Ptr->next;
}
Ptr->next = n;
}
}
...
解决方案
使用地图,但你需要一些东西来用作散列。也许书名?
std::map<std::string, Book> bookMap;
然后,您可以通过以下方式访问书籍:
bookMap["Flowers for Algernon"]
插入有点棘手。
ptr = bookMap( pair<string, Book>("The Old Man of the Sea", myBook) );
推荐阅读
- r - 可以自定义 tbl_summary() 以在页脚显示重要性星吗?
- javascript - footable 3.1.5 过滤图标方向同时显示上下
- spring-boot - 用于 ManyToOne 而不是链接的 Spring PagingAndSorting 存储库加载对象
- ios - 从实时数据库中获取图像 URL - Firebase / Swift
- algorithm - 包含限制的 TSP 的 Bellman-Held-Karp 算法
- r - 用 mutate 函数替换条件下的值
- python - 如何使用函数列表来更新字典列表的值?
- perl - Perl while循环打印来自不同来源的行
- r - Bookdown:为什么最终文档标题变成了项目标题?
- node.js - 将大量模块导入一个地方