c++哈希表的实现以及const和static

#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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值