【C++航海王:追寻罗杰的编程之路】一篇文章带你认识哈希

本文涉及的产品
函数计算FC,每月15万CU 3个月
简介: 【C++航海王:追寻罗杰的编程之路】一篇文章带你认识哈希

1 -> unordered系列关联式容器

在C++98中,STL提供了底层为红黑树结构的一系列关联式容器,在查询时效率可达到O(n),即最差情况下需要比较红黑树的高度次,当树中的节点非常多时,查询效率也不理想。最好的查询是进行很少的比较次数就能将元素找到,因此在C++11中,STL又提供了4个unordered系列的关联式容器,这四个容器与红黑树结构的关联式容器使用方式基本类似,只是其底层结构不同。

1.1 -> unordered_map

1.1.1 -> unordered_map的文档介绍

unordered_map文档说明


unordered_map是存储<key,value>键值对的关联式容器,其允许通过keys快速的索引到与其对应的value。

在unordered_map中,键值通常用于唯一地标识元素,而映射值是一个对象,其内容与此键关联。键和映射值的类型可能不同。

在内部unordered_map没有对<key,value>按照任何特定的顺序排序,为了能在常数范围内找到key所对应的value,unordered_map将相同的哈希值的键值对放在相同的桶中。

unordered_map容器通过key访问单个元素要比map快,但它通常在遍历元素子集的范围迭代方面效率较低。

unordered_map实现了直接访问操作符(operator[]),它允许使用key作为参数直接访问value。

它的迭代器至少是前向迭代器。

1.1.2 -> unordered_map的接口说明

1. unordered_map的构造

函数声明 功能介绍
unordered_map 构造不同格式的unordered_map对象


2. unordered_map的容量

函数声明 功能介绍
bool empty() const 检测unordered_map是否为空
size_t size() const 获取unordered_map的有效元素个数


3. unordered_map的迭代器

image.png

4. unordered_map的元素访问

函数声明 功能介绍
operator[] 返回与key对应的value,没有一个默认值


注意:该函数中实际调用哈希桶的插入操作,用参数key与V()构造一个默认值往底层哈希桶中插入,如果key不在哈希桶中,插入成功,返回V(),插入失败,说明key已经在哈希桶中,将key对应的value返回。

5. unordered_map的查询

image.png

注意:unordered_map中key是不能重复的,因此count函数的返回值最大为1。

6. unordered_map的修改操作

image.png

7. unordered_map的桶操作

image.png

1.2 -> unordered_set

unordered_set文档说明

2 -> 底层结构

unordered系列的关联式容器之所以效率比较高,是因为其底层使用了哈希结构。

2.1 -> 哈希概念

顺序结构以及平衡树中,元素关键码与其存储位置之间没有对应的关系,因此在查找一个元素时,必须要经过关键码的多次比较。顺序查找时间复杂度为O(N),平衡树中为树的高度,即O(N),搜索的效率取决于搜索过程中元素的比较次数。


理想的搜索方法:可以不经过任何比较,一次直接从表中得到要搜索的元素。如果构造一种存储结构,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立——映射的关系,那么在查找时通过该函数可以很快找到该元素。


当向该结构中:

  • 插入元素

根据待插入元素的关键码,以此函数计算出该元素的存储位置并按此位置进行存放。

  • 搜索元素

对元素的关键码进行同样的计算,把求得的函数值当作元素的存储位置,在结构中按此位置取元素比较,若关键码相等,则搜索成功。


该方式即为哈希(散列)方法,哈希方法中使用的转换函数称为哈希(散列)函数,构造出的结构称为哈希表(Hash Table)(或者称散列表)。


例如:数据集合{1,7,6,4,5,9};


哈希函数设置为:hash(key) = key % capacity;capacity为存储元素底层空间的总大小。

用该方法进行搜索不必进行多次关键码的比较,因此搜索的速度比较快。

2.2 -> 哈希冲突

不同关键字通过相同哈希函数计算出相同的哈希地址,该种现象称为哈希冲突或哈希碰撞。

把具有不同关键码而具有相同哈希地址的数据元素称为“同义词”。

2.3 -> 哈希函数

引起哈希冲突的一个原因可能是:哈希函数设计不够合理。


哈希函数设计原则:


哈希函数的定义域必须包括需要存储的全部关键码,而如果散列表允许有m个地址时,其值域必须在0到m-1之间。

哈希函数计算出来的地址能均匀分布在整个空间中。

哈希函数应该比较简单。

常见哈希函数


1.  直接定址法--(常用)


取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B。


优点:简单、均匀。


缺点:需要事先知道关键字的分布情况。


缺点:需要事先知道关键字的分布情况。


2.  除留余数法--(常用)


设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数,按照哈希函数:Hash(key) = key% p(p<=m),将关键码转换成哈希地址。


3.  平方取中法


假设关键字为1234,对它平方就是1522756,抽取中间的3位227作为哈希地址;再比如关键字为4321,对它平方就是18671041,抽取中间的3位671(或710)作为哈希地址。


平方取中法比较适合:不知道关键字的分布,而位数又不是很大的情况。


4.  折叠法


折叠法是将关键字从左到右分割成位数相等的几部分(最后一部分位数可以短些),然后将这几部分叠加求和,并按散列表表长,取后几位作为散列地址。


折叠法适合事先不需要知道关键字的分布,适合关键字位数比较多的情况。


5.  随机数法


选择一个随机函数,取关键字的随机函数值为它的哈希地址,即H(key) = random(key),其中random为随机数函数。


通常应用于关键字长度不等时采用此法。


6.  数学分析法


设有n个d位数,每一位可能有r种不同的符号,这r种不同的符号在各位上出现的频率不一定

相同,可能在某些位上分布比较均匀,每种符号出现的机会均等,在某些位上分布不均匀只

有某几种符号经常出现。可根据散列表的大小,选择其中各种符号分布均匀的若干位作为散

列地址。


数字分析法通常适合处理关键字位数比较大的情况,如果事先知道关键字的分布且关键字的若干位分布较均匀的情况。


注意:哈希函数设计的越精妙,产生哈希冲突的可能性就越低,但是无法避免哈希冲突。

2.4 -> 哈希冲突解决

解决哈希冲突两种常见的方法是:闭散列开散列

2.4.1 -> 闭散列

闭散列:也叫开放定址法,当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有

空位置,那么可以把key存放到冲突位置中的“下一个” 空位置中去。


1. 线性探测


比如2.1中的场景,现在需要插入元素44,先通过哈希函数计算哈希地址,hashAddr为4,因此44理论上应该插在该位置,但是该位置已经放了值为4的元素,即发生哈希冲突。


线性探测:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。


插入:


通过哈希函数获取待插入元素在哈希表中的位置。

如果该位置中没有元素则直接插入新元素,如果该位置中有元素发生哈希冲突,使用线性探测找到下一个空位置,插入新元素。

删除:

采用闭散列处理哈希冲突时,不能随便物理删除哈希表中已有的元素,若直接删除元素会影响其他元素的搜索。比如删除元素4,如果直接删除掉,44查找起来可能会受影响。因此线性探测采用标记的伪删除法来删除一个元素。

#define _CRT_SECURE_NO_WARNINGS 1
 
#include <iostream>
using namespace std;
 
// 哈希表每个空间给个标记
// EMPTY此位置空, EXIST此位置已经有元素, DELETE元素已经删除
enum State 
{ 
  EMPTY, EXIST, DELETE 
};

线性探测实现:

#define _CRT_SECURE_NO_WARNINGS 1
 
#include <iostream>
using namespace std;
 
// 哈希表每个空间给个标记
// EMPTY此位置空, EXIST此位置已经有元素, DELETE元素已经删除
enum State 
{ 
  EMPTY, EXIST, DELETE 
};
 
// 注意:假如实现的哈希表中元素唯一,即key相同的元素不再进行插入
// 为了实现简单,此哈希表中我们将比较直接与元素绑定在一起
template<class K, class V>
class HashTable
{
  struct Elem
  {
    pair<K, V> _val;
    State _state;
  };
 
public:
  HashTable(size_t capacity = 3)
    : _ht(capacity), _size(0)
  {
    for (size_t i = 0; i < capacity; ++i)
      _ht[i]._state = EMPTY;
  }
 
  bool Insert(const pair<K, V>& val)
  {
    // 检测哈希表底层空间是否充足
    // _CheckCapacity();
    size_t hashAddr = HashFunc(key);
 
    // size_t startAddr = hashAddr;
    while (_ht[hashAddr]._state != EMPTY)
    {
      if (_ht[hashAddr]._state == EXIST && _ht[hashAddr]._val.first
        == key)
        return false;
 
      hashAddr++;
      if (hashAddr == _ht.capacity())
        hashAddr = 0;
    /*
    // 转一圈也没有找到,注意:动态哈希表,该种情况可以不用考虑,哈希表中元
    素个数到达一定的数量,哈希冲突概率会增大,需要扩容来降低哈希冲突,
    因此哈希表中元素是不会存满的
       if(hashAddr == startAddr)
        return false;
    */
    }
 
    // 插入元素
    _ht[hashAddr]._state = EXIST;
    _ht[hashAddr]._val = val;
    _size++;
 
    return true;
  }
 
  int Find(const K& key)
  {
    size_t hashAddr = HashFunc(key);
    while (_ht[hashAddr]._state != EMPTY)
    {
      if (_ht[hashAddr]._state == EXIST && 
        _ht[hashAddr]._val.first == key)
        return hashAddr;
 
      hashAddr++;
    }
 
    return hashAddr;
  }
  bool Erase(const K & key)
  {
    int index = Find(key);
    if (-1 != index)
    {
      _ht[index]._state = DELETE;
      _size++;
 
      return true;
    }
 
    return false;
  }
 
  size_t Size()const;
  bool Empty() const;
  void Swap(HashTable<K, V, HF>&ht);
 
private:
  size_t HashFunc(const K & key)
  {
    return key % _ht.capacity();
  }
 
private:
  vector<Elem> _ht;
  size_t _size;
};

线性探测的优点:实现非常简单。


线性探测的缺点:一旦发生哈希冲突,所有的冲突连在一起,容易产生数据“堆积”,即:不同关键码占据了可利用的空位置,使得寻找某关键码的位置需要多次比较,导致搜索效率降低。


2. 二次探测


线性探测的缺陷是产生冲突的数据堆积在一块,这与其找下一个空位置有关系,因为找空位置的方式就是挨着往后逐个去找,因此二次探测为了避免该问题。

研究表明:当表的长度为质数且表装载因子a不超过0.5时,新的表项一定能够插入,而且任何一个位置都不会被探查两次。因此只要表中有一半的空位置,就不会存在表满的问题。在搜索时可以不考虑表装满的情况,但在插入时必须确保表的装载因子a不超过0.5,如果超出必须考虑增容。


因此:闭散列最大的缺陷就是空间利用率比较低,这也是哈希的缺陷。

2.4.2 -> 开散列

1. 开散列概念

开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中。

从上图可以看出,开散列中每个桶中放的都是发生哈希冲突的元素。

2. 开散列实现

#define _CRT_SECURE_NO_WARNINGS 1
 
#include <iostream>
using namespace std;
 
template<class V>
struct HashBucketNode
{
  HashBucketNode(const V& data)
    : _pNext(nullptr), _data(data)
  {}
  HashBucketNode<V>* _pNext;
  V _data;
};
 
// 所实现的哈希桶中key是唯一的
template<class V>
class HashBucket
{
  typedef HashBucketNode<V> Node;
  typedef Node* PNode;
 
public:
  HashBucket(size_t capacity = 3) : _size(0)
  {
    _ht.resize(GetNextPrime(capacity), nullptr);
  }
 
  // 哈希桶中的元素不能重复
  PNode* Insert(const V& data)
  {
    // 确认是否需要扩容。。。
     // _CheckCapacity();
 
    // 1. 计算元素所在的桶号
    size_t bucketNo = HashFunc(data);
 
    // 2. 检测该元素是否在桶中
    PNode pCur = _ht[bucketNo];
    while (pCur)
    {
      if (pCur->_data == data)
        return pCur;
 
      pCur = pCur->_pNext;
    }
 
    // 3. 插入新元素
    pCur = new Node(data);
    pCur->_pNext = _ht[bucketNo];
    _ht[bucketNo] = pCur;
    _size++;
 
    return pCur;
  }
 
  // 删除哈希桶中为data的元素(data不会重复),返回删除元素的下一个节点
  PNode* Erase(const V& data)
  {
    size_t bucketNo = HashFunc(data);
    PNode pCur = _ht[bucketNo];
    PNode pPrev = nullptr, pRet = nullptr;
 
    while (pCur)
    {
      if (pCur->_data == data)
      {
        if (pCur == _ht[bucketNo])
          _ht[bucketNo] = pCur->_pNext;
        else
          pPrev->_pNext = pCur->_pNext;
 
        pRet = pCur->_pNext;
        delete pCur;
        _size--;
 
        return pRet;
      }
    }
 
    return nullptr;
  }
 
  PNode* Find(const V& data);
  size_t Size()const;
  bool Empty()const;
  void Clear();
  bool BucketCount()const;
  void Swap(HashBucket<V, HF>& ht;
  ~HashBucket();
 
private:
  size_t HashFunc(const V& data)
  {
    return data % _ht.capacity();
  }
 
private:
  vector<PNode*> _ht;
  size_t _size; // 哈希表中有效元素的个数
};

3. 开散列增容

桶的个数是一定的,随着元素的不断插入,每个桶中元素的个数不断增多,极端情况下,可能会导致一个桶中链表节点非常多,会影响的哈希表的性能,因此在一定条件下需要对哈希表进行增容,那该条件怎么确认呢?开散列最好的情况是:每个哈希桶中刚好挂一个节点,再继续插入元素时,每一次都会发生哈希冲突,因此,在元素个数刚好等于桶的个数时,可以给哈希表增容。

void _CheckCapacity()
  {
    size_t bucketCount = BucketCount();
    if (_size == bucketCount)
    {
      HashBucket<V, HF> newHt(bucketCount);
      for (size_t bucketIdx = 0; bucketIdx < bucketCount; ++bucketIdx)
      {
        PNode pCur = _ht[bucketIdx];
        while (pCur)
        {
          // 将该节点从原哈希表中拆出来
          _ht[bucketIdx] = pCur->_pNext;
 
          // 将该节点插入到新哈希表中
          size_t bucketNo = newHt.HashFunc(pCur->_data);
          pCur->_pNext = newHt._ht[bucketNo];
          newHt._ht[bucketNo] = pCur;
          pCur = _ht[bucketIdx];
        }
      }
 
      newHt._size = _size;
      this->Swap(newHt);
    }
  }

4. 开散列的思考

(1)只能存储key为整形的元素,其他类型怎么解决?

// 哈希函数采用处理余数法,被模的key必须要为整形才可以处理,此处提供将key转化为整形的方法
// 整形数据不需要转化
template<class T>
class DefHashF
{
public:
  size_t operator()(const T& val)
  {
    return val;
  }
};
 
// key为字符串类型,需要将其转化为整形
class Str2Int
{
public:
  size_t operator()(const string& s)
  {
    const char* str = s.c_str();
    unsigned int seed = 131; // 31 131 1313 13131 131313
    unsigned int hash = 0;
    while (*str)
    {
      hash = hash * seed + (*str++);
    }
 
    return (hash & 0x7FFFFFFF);
  }
};
 
// 为了实现简单,此哈希表中我们将比较直接与元素绑定在一起
template<class V, class HF>
class HashBucket
{
  // ……
private:
  size_t HashFunc(const V& data)
  {
    return HF()(data.first) % _ht.capacity();
  }
};

(2)除留余数法,最好模一个素数,如何每次快速取一个类似两倍关系的素数?

size_t GetNextPrime(size_t prime)
{
  const int PRIMECOUNT = 28;
  static const size_t primeList[PRIMECOUNT] =
  {
  53ul, 97ul, 193ul, 389ul, 769ul,
  1543ul, 3079ul, 6151ul, 12289ul, 24593ul,
  49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
  1572869ul, 3145739ul, 6291469ul, 12582917ul,
   25165843ul,
  50331653ul, 100663319ul, 201326611ul, 402653189ul,
   805306457ul,
  1610612741ul, 3221225473ul, 4294967291ul
  };
 
  size_t i = 0;
  for (; i < PRIMECOUNT; ++i)
  {
    if (primeList[i] > prime)
      return primeList[i];
  }
 
  return primeList[i];
}

5. 开散列与闭散列比较

应用链地址法处理溢出,需要增设链接指针,似乎增加了存储开销。事实上:由于开地址法必须保持大量的空闲空间以确保搜索效率,如二次探查法要求装载因子a <= 0.7,而表项所占空间又比指针大的多,所以使用链地址法反而比开地址法节省存储空间。

3 -> 模拟实现

3.1 -> 哈希表的改造

#pragma once
 
//HashFunc<int>
template<class K>
struct HashFunc
{
  size_t operator()(const K& key)
  {
    return (size_t)key;
  }
};
 
//HashFunc<string>
template<>
struct HashFunc<string>
{
  size_t operator()(const string& key)
  {
    // BKDR
    size_t hash = 0;
    for (auto e : key)
    {
      hash *= 31;
      hash += e;
    }
 
    //cout << key << ":" << hash << endl;
    return hash;
  }
};
 
namespace open_address
{
  enum Status
  {
    EMPTY,
    EXIST,
    DELETE
  };
 
  template<class K, class V>
  struct HashData
  {
    pair<K, V> _kv;
    Status _s;          //状态
  };
 
  //struct HashFuncString
  //{
  //  size_t operator()(const string& key)
  //  {
  //    // BKDR
  //    size_t hash = 0;
  //    for (auto e : key)
  //    {
  //      hash *= 31;
  //      hash += e;
  //    }
 
  //    cout << key << ":" << hash << endl;
  //    return hash;
  //  }
  //};
 
  template<class K, class V, class Hash = HashFunc<K>>
  class HashTable
  {
  public:
    HashTable()
    {
      _tables.resize(10);
    }
 
    bool Insert(const pair<K, V>& kv)
    {
      if (Find(kv.first))
        return false;
 
      // 负载因子0.7就扩容
      if (_n * 10 / _tables.size() == 7)
      {
        size_t newSize = _tables.size() * 2;
        HashTable<K, V, Hash> newHT;
        newHT._tables.resize(newSize);
 
        // 遍历旧表
        for (size_t i = 0; i < _tables.size(); i++)
        {
          if (_tables[i]._s == EXIST)
          {
            newHT.Insert(_tables[i]._kv);
          }
        }
 
        _tables.swap(newHT._tables);
      }
 
      Hash hf;
      // 线性探测
      size_t hashi = hf(kv.first) % _tables.size();
      while (_tables[hashi]._s == EXIST)
      {
        hashi++;
 
        hashi %= _tables.size();
      }
 
      _tables[hashi]._kv = kv;
      _tables[hashi]._s = EXIST;
      ++_n;
 
      return true;
    }
 
    HashData<K, V>* Find(const K& key)
    {
      Hash hf;
 
      size_t hashi = hf(key) % _tables.size();
      while (_tables[hashi]._s != EMPTY)
      {
        if (_tables[hashi]._s == EXIST
          && _tables[hashi]._kv.first == key)
        {
          return &_tables[hashi];
        }
 
        hashi++;
        hashi %= _tables.size();
      }
 
      return NULL;
    }
 
    // 伪删除法
    bool Erase(const K& key)
    {
      HashData<K, V>* ret = Find(key);
      if (ret)
      {
        ret->_s = DELETE;
        --_n;
 
        return true;
      }
      else
      {
        return false;
      }
    }
 
    void Print()
    {
      for (size_t i = 0; i < _tables.size(); i++)
      {
        if (_tables[i]._s == EXIST)
        {
          //printf("[%d]->%d\n", i, _tables[i]._kv.first);
          cout << "[" << i << "]->" << _tables[i]._kv.first << ":" << _tables[i]._kv.second << endl;
        }
        else if (_tables[i]._s == EMPTY)
        {
          printf("[%d]->\n", i);
        }
        else
        {
          printf("[%d]->D\n", i);
        }
      }
 
      cout << endl;
    }
 
  private:
    vector<HashData<K, V>> _tables;
    size_t _n = 0; // 存储的关键字的个数
  };
 
  void TestHT1()
  {
    HashTable<int, int> ht;
    int a[] = { 4,14,24,34,5,7,1 };
    for (auto e : a)
    {
      ht.Insert(make_pair(e, e));
    }
 
    ht.Insert(make_pair(3, 3));
    ht.Insert(make_pair(3, 3));
    ht.Insert(make_pair(-3, -3));
    ht.Print();
 
    ht.Erase(3);
    ht.Print();
 
    if (ht.Find(3))
    {
      cout << "3存在" << endl;
    }
    else
    {
      cout << "3不存在" << endl;
    }
 
    ht.Insert(make_pair(3, 3));
    ht.Insert(make_pair(23, 3));
    ht.Print();
  }
 
  void TestHT2()
  {
    string arr[] = { "香蕉", "甜瓜","苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉" };
    //HashTable<string, int, HashFuncString> ht;
    HashTable<string, int> ht;
    for (auto& e : arr)
    {
      //auto ret = ht.Find(e);
      HashData<string, int>* ret = ht.Find(e);
      if (ret)
      {
        ret->_kv.second++;
      }
      else
      {
        ht.Insert(make_pair(e, 1));
      }
    }
 
    ht.Print();
 
    ht.Insert(make_pair("apple", 1));
    ht.Insert(make_pair("sort", 1));
 
    ht.Insert(make_pair("abc", 1));
    ht.Insert(make_pair("acb", 1));
    ht.Insert(make_pair("aad", 1));
 
    ht.Print();
  }
}
 
namespace hash_bucket
{
  template<class T>
  struct HashNode
  {
    HashNode<T>* _next;
    T _data;
 
    HashNode(const T& data)
      :_data(data)
      , _next(nullptr)
    {}
  };
 
  // 前置声明
  template<class K, class T, class KeyOfT, class Hash>
  class HashTable;
 
  template<class K, class T, class Ref, class Ptr, class KeyOfT, class Hash>
  struct __HTIterator
  {
    typedef HashNode<T> Node;
    typedef __HTIterator<K, T, Ref, Ptr, KeyOfT, Hash> Self;
    Node* _node;
    const HashTable<K, T, KeyOfT, Hash>* _pht;
 
    // vector<Node*> * _ptb;
 
    size_t _hashi;
 
    __HTIterator(Node* node, HashTable<K, T, KeyOfT, Hash>* pht, size_t hashi)
      :_node(node)
      , _pht(pht)
      , _hashi(hashi)
    {}
 
    __HTIterator(Node* node, const HashTable<K, T, KeyOfT, Hash>* pht, size_t hashi)
      :_node(node)
      , _pht(pht)
      , _hashi(hashi)
    {}
 
    Self& operator++()
    {
      if (_node->_next)
      {
        // 当前桶还有节点,走到下一个节点
        _node = _node->_next;
      }
      else
      {
        // 当前桶已经走完了,找下一个桶开始
        //KeyOfT kot;
        //Hash hf;
        //size_t hashi = hf(kot(_node->_data)) % _pht._tables.size();
        ++_hashi;
        while (_hashi < _pht->_tables.size())
        {
          if (_pht->_tables[_hashi])
          {
            _node = _pht->_tables[_hashi];
            break;
          }
 
          ++_hashi;
        }
 
        if (_hashi == _pht->_tables.size())
        {
          _node = nullptr;
        }
      }
 
      return *this;
    }
 
    Ref operator*()
    {
      return _node->_data;
    }
 
    Ptr operator->()
    {
      return &_node->_data;
    }
 
    bool operator!=(const Self& s)
    {
      return _node != s._node;
    }
  };
 
  // unordered_set -> Hashtable<K, K>
  // unordered_map -> Hashtable<K, pair<K, V>>
  template<class K, class T, class KeyOfT, class Hash>
  class HashTable
  {
    typedef HashNode<T> Node;
 
    template<class K, class T, class Ref, class Ptr, class KeyOfT, class Hash>
    friend struct __HTIterator;
 
  public:
    typedef __HTIterator<K, T, T&, T*, KeyOfT, Hash> iterator;
    typedef __HTIterator<K, T, const T&, const T*, KeyOfT, Hash> const_iterator;
 
    iterator begin()
    {
      for (size_t i = 0; i < _tables.size(); i++)
      {
        if (_tables[i])
        {
          return iterator(_tables[i], this, i);
        }
      }
 
      return end();
    }
 
    iterator end()
    {
      return iterator(nullptr, this, -1);
    }
 
    const_iterator begin() const
    {
      for (size_t i = 0; i < _tables.size(); i++)
      {
        if (_tables[i])
        {
          return const_iterator(_tables[i], this, i);
        }
      }
 
      return end();
    }
 
    // this-> const HashTable<K, T, KeyOfT, Hash>*
    const_iterator end() const
    {
      return const_iterator(nullptr, this, -1);
    }
 
    HashTable()
    {
      _tables.resize(10);
    }
 
    ~HashTable()
    {
      for (size_t i = 0; i < _tables.size(); i++)
      {
        Node* cur = _tables[i];
        while (cur)
        {
          Node* next = cur->_next;
          delete cur;
          cur = next;
        }
        _tables[i] = nullptr;
      }
    }
 
    pair<iterator, bool> Insert(const T& data)
    {
      Hash hf;
      KeyOfT kot;
 
      iterator it = Find(kot(data));
      if (it != end())
        return make_pair(it, false);
 
      // 负载因子最大到1
      if (_n == _tables.size())
      {
        vector<Node*> newTables;
        newTables.resize(_tables.size() * 2, nullptr);
        // 遍历旧表
        for (size_t i = 0; i < _tables.size(); i++)
        {
          Node* cur = _tables[i];
          while (cur)
          {
            Node* next = cur->_next;
 
            // 挪动到映射的新表
            size_t hashi = hf(kot(cur->_data)) % newTables.size();
            cur->_next = newTables[i];
            newTables[hashi] = cur;
 
            cur = next;
          }
 
          _tables[i] = nullptr;
        }
 
        _tables.swap(newTables);
      }
 
      size_t hashi = hf(kot(data)) % _tables.size();
      Node* newnode = new Node(data);
 
      // 头插
      newnode->_next = _tables[hashi];
      _tables[hashi] = newnode;
      ++_n;
 
      return make_pair(iterator(newnode, this, hashi), true);
    }
 
    iterator Find(const K& key)
    {
      Hash hf;
      KeyOfT kot;
 
      size_t hashi = hf(key) % _tables.size();
      Node* cur = _tables[hashi];
      while (cur)
      {
        if (kot(cur->_data) == key)
        {
          return iterator(cur, this, hashi);
        }
 
        cur = cur->_next;
      }
 
      return end();
    }
 
    bool Erase(const K& key)
    {
      Hash hf;
      KeyOfT kot;
 
      size_t hashi = hf(key) % _tables.size();
      Node* prev = nullptr;
      Node* cur = _tables[hashi];
      while (cur)
      {
        if (kot(cur->_data) == key)
        {
          if (prev == nullptr)
          {
            _tables[hashi] = cur->_next;
          }
          else
          {
            prev->_next = cur->_next;
          }
          delete cur;
 
          return true;
        }
 
        prev = cur;
        cur = cur->_next;
      }
 
      return false;
    }
 
    void Some()
    {
      size_t bucketSize = 0;
      size_t maxBucketLen = 0;
      size_t sum = 0;
      double averageBucketLen = 0;
 
      for (size_t i = 0; i < _tables.size(); i++)
      {
        Node* cur = _tables[i];
        if (cur)
        {
          ++bucketSize;
        }
 
        size_t bucketLen = 0;
        while (cur)
        {
          ++bucketLen;
          cur = cur->_next;
        }
 
        sum += bucketLen;
        if (bucketLen > maxBucketLen)
        {
          maxBucketLen = bucketLen;
        }
      }
 
      averageBucketLen = (double)sum / (double)bucketSize;
 
      printf("all bucketSize:%d\n", _tables.size());
      printf("bucketSize:%d\n", bucketSize);
      printf("maxBucketLen:%d\n", maxBucketLen);
      printf("averageBucketLen:%lf\n\n", averageBucketLen);
    }
 
  private:
    vector<Node*> _tables;
    size_t _n = 0;
  };
}

3.2 -> unordered_map

#pragma once
#include"HashTable.h"
 
namespace fyd
{
  template<class K, class V, class Hash = HashFunc<K>>
  class unordered_map
  {
    struct MapKeyOfT
    {
      const K& operator()(const pair<K, V>& kv)
      {
        return kv.first;
      }
    };
 
  public:
    typedef typename hash_bucket::HashTable<K, pair<const K, V>, MapKeyOfT, Hash>::iterator iterator;
 
    iterator begin()
    {
      return _ht.begin();
    }
 
    iterator end()
    {
      return _ht.end();
    }
 
    pair<iterator, bool> insert(const pair<K, V>& kv)
    {
      return _ht.Insert(kv);
    }
 
    V& operator[](const K& key)
    {
      pair<iterator, bool> ret = _ht.Insert(make_pair(key, V()));
 
      return ret.first->second;
    }
 
    const V& operator[](const K& key) const
    {
      pair<iterator, bool> ret = _ht.Insert(make_pair(key, V()));
 
      return ret.first->second;
    }
 
    iterator find(const K& key)
    {
      return _ht.Find(key);
    }
 
    bool erase(const K& key)
    {
      return _ht.Erase(key);
    }
 
  private:
    hash_bucket::HashTable<K, pair<const K, V>, MapKeyOfT, Hash> _ht;
  };
 
  void test_map()
  {
    unordered_map<string, string> dict;
    dict.insert(make_pair("sort", ""));
    dict.insert(make_pair("string", "ַ"));
    dict.insert(make_pair("insert", ""));
 
    for (auto& kv : dict)
    {
      //kv.first += 'x';
      kv.second += 'x';
 
      cout << kv.first << ":" << kv.second << endl;
    }
    cout << endl;
 
    string arr[] = { "㽶", "","ƻ", "", "ƻ", "", "ƻ", "ƻ", "", "ƻ", "㽶", "ƻ", "㽶" };
    unordered_map<string, int> count_map;
    for (auto& e : arr)
    {
      count_map[e]++;
    }
 
    for (auto& kv : count_map)
    {
      cout << kv.first << ":" << kv.second << endl;
    }
    cout << endl;
  }
}

3.3 -> unordered_set

#pragma once
#include"HashTable.h"
 
namespace fyd
{
  template<class K, class Hash = HashFunc<K>>
  class unordered_set
  {
    struct SetKeyOfT
    {
      const K& operator()(const K& key)
      {
        return key;
      }
    };
  public:
    typedef typename hash_bucket::HashTable<K, K, SetKeyOfT, Hash>::const_iterator iterator;
    typedef typename hash_bucket::HashTable<K, K, SetKeyOfT, Hash>::const_iterator const_iterator;
 
    /*iterator begin()
    {
      return _ht.begin();
    }
 
    iterator end()
    {
      return _ht.end();
    }*/
 
    const_iterator begin() const
    {
      return _ht.begin();
    }
 
    const_iterator end() const
    {
      return _ht.end();
    }
 
    pair<const_iterator, bool> insert(const K& key)
    {
      auto ret = _ht.Insert(key);
      return pair<const_iterator, bool>(const_iterator(ret.first._node, ret.first._pht, ret.first._hashi), ret.second);
    }
 
    iterator find(const K& key)
    {
      return _ht.Find(key);
    }
 
    bool erase(const K& key)
    {
      return _ht.Erase(key);
    }
  private:
    hash_bucket::HashTable<K, K, SetKeyOfT, Hash> _ht;
  };
 
  void test_set()
  {
    unordered_set<int> us;
    us.insert(5);
    us.insert(15);
    us.insert(52);
    us.insert(3);
 
    unordered_set<int>::iterator it = us.begin();
    while (it != us.end())
    {
      //*it += 5;
      cout << *it << " ";
      ++it;
    }
    cout << endl;
 
    for (auto e : us)
    {
      cout << e << " ";
    }
    cout << endl;
  }
}
 
相关实践学习
【文生图】一键部署Stable Diffusion基于函数计算
本实验教你如何在函数计算FC上从零开始部署Stable Diffusion来进行AI绘画创作,开启AIGC盲盒。函数计算提供一定的免费额度供用户使用。本实验答疑钉钉群:29290019867
建立 Serverless 思维
本课程包括: Serverless 应用引擎的概念, 为开发者带来的实际价值, 以及让您了解常见的 Serverless 架构模式
目录
相关文章
|
18天前
|
存储 算法 C++
【算法】哈希映射(C/C++)
【算法】哈希映射(C/C++)
|
2月前
|
C++ 容器
【C++航海王:追寻罗杰的编程之路】关于空间配置器你知道多少?
【C++航海王:追寻罗杰的编程之路】关于空间配置器你知道多少?
30 2
|
2月前
|
算法 C语言 C++
【C++航海王:追寻罗杰的编程之路】C++的IO流
【C++航海王:追寻罗杰的编程之路】C++的IO流
31 2
|
2月前
|
存储 搜索推荐 Serverless
【C++航海王:追寻罗杰的编程之路】哈希的应用——位图 | 布隆过滤器
【C++航海王:追寻罗杰的编程之路】哈希的应用——位图 | 布隆过滤器
31 1
|
2月前
|
存储 缓存 NoSQL
【C++】哈希容器
【C++】哈希容器
|
2月前
|
安全 C++
【C++航海王:追寻罗杰的编程之路】智能指针
【C++航海王:追寻罗杰的编程之路】智能指针
32 0
|
5天前
|
存储 编译器 对象存储
【C++打怪之路Lv5】-- 类和对象(下)
【C++打怪之路Lv5】-- 类和对象(下)
15 4
|
5天前
|
编译器 C语言 C++
【C++打怪之路Lv4】-- 类和对象(中)
【C++打怪之路Lv4】-- 类和对象(中)
15 4
|
5天前
|
存储 安全 C++
【C++打怪之路Lv8】-- string类
【C++打怪之路Lv8】-- string类
10 1
|
15天前
|
存储 编译器 C++
【C++类和对象(下)】——我与C++的不解之缘(五)
【C++类和对象(下)】——我与C++的不解之缘(五)