#include<iostream>
#include<unordered_map>
#include <string>
#include <math.h>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <list>
using namespace std;
template <typename T>
class HashTable {
private:
vector<list<T>> hash_table;
// 哈希函数
int myhash(const T & obj) const {
return hash(obj, hash_table.size());
}
public:
// size最好是质数
HashTable(int size=31) {//构造函数
hash_table.reserve(size);
hash_table.resize(size);
}
~HashTable() {}//析构函数
// 查找哈希表是否存在该值
bool contains(const T & obj) {
int hash_value = myhash(obj);
const list<T> & slot = hash_table[hash_value];
typename list<T>::const_iterator it = slot.cbegin();
for (; it != slot.cend() && *it != obj; ++it);
return it != slot.cend();
}
// 插入值
bool insert(const T & obj) {
if (contains(obj)) {
return false;
}
int hash_value = myhash(obj);
std::list<T> & slot = hash_table[hash_value];
slot.push_front(obj);
return true;
}
// 删除值
bool remove(const T & obj) {
list<T> & slot = hash_table[myhash(obj)];
auto it = find(slot.begin(), slot.end(), obj);
if (it == slot.end()) {
return false;
}
slot.erase(it);
return true;
}
int hash(const int & key, const int &tableSize) {
return key % tableSize;
}//这个函数是构建键与值的对应
};
在这一段代码中,出现一个问题,之前在list的迭代器之前没有加typename,报错Missing ‘typename’ prior to dependent type name ‘list::iterator’。**这个问题产生原因是编译器不能识别"XXXX::XX"是个啥,这到底是个类型呢,还是类得静态成员变量呢?**于是在前面加上typename,告诉编译器这是一个类型不是一个变量。
此处在讲一下const以及static
const定义的常量在函数执行之后其空间会被释放,而static定义的静态常量在函数执行后不会被释放其空间。
static 表示的是静态的。类的静态成员函数,成员变量是和类相关的,不是和类的具体对象相关,即使没有具体的对象,也能调用类的静态成员函数,成员变量。一般的静态函数几乎就是一个全局函数,只不过它的作用域限于包含它的文件中。
在c++中,static静态成员变量不能在类内部初始化。
在c++中,const常量成员变量也不能在类定义处初始化,只能通过构造函数初始化列表进行,并且必须有构造函数。
const数据成员只在某个对象生存期内是常量,而对于整个类而言却是可变的。因为类可以创建多个对象,不同的对象其const数据成员的值可以不同(意思在定义的类之内,const数据是可变的)。所以不能在类声明中初始化const数据成员,因为类的对象未被创建时,编译器不知道const 数据成员的值是什么。
const数据成员的初始化只能在类的构造函数的初始化表中进行。要想建立在整个类中都恒定的常量,应该用类中的枚举常量来实现,或者static const。