1 散列表简介
- 散列表是词典的一种形态,散列表通过“循值”访问数据,其动态特性与静态特性都十分优秀
- 散列表具支持多个词条拥有相同的关键码
- 散列表的关键是散列函数的设计,随机性强、规律性弱的散列函数最好
散列表的支持的接口如下:
操作接口 | 功能描述 |
---|---|
get(key) | 若词典存在以key为关键码的词条,返回该词条的数据对象;否则返回NULL |
put(key, value) | 插入词条(key, value),并报告是否成功 |
remove(key) | 若词典存在以key为关键码的词条,删除之并返回true;否则返回false |
2 散列表包含的头文件
实现散列表需要包含一些头文件,包括"dictionary.h", “bitmap.h”, “entry.h”。其中,"dictionary.h"是词典的类,供散列表头文件改写函数接口;"bitmap.h"是位图的头文件,功能是为懒惰删除标志提高操作函数;"entry.h"包含一个含有(key, value)的结构体。
这三个头文件的源文件如下:
//"dictionary.h"
#pragma once
template <typename K, typename V> struct Dictionary {
//词典Dictionary模板类
virtual int size() const = 0; //当前词条总数
virtual bool put ( K, V ) = 0; //插入词条(禁止雷同词条时可能失败)
virtual V* get ( K k ) = 0; //读取词条
virtual bool remove ( K k ) = 0; //删除词条
};
//"bitmap.h"
//"../dsa_bintree_20200720/release.h"可见https://blog.csdn.net/weixin_41698717/article/details/107541482
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <cstring>
#include "../dsa_bintree_20200720/release.h"
class Bitmap {
//位图Bitmap类
private:
char* M; int N; //比特图所存放的空间M[],容量为N*sizeof(char)*8比特
protected:
void init ( int n ) {
M = new char[N = ( n + 7 ) / 8]; memset ( M, 0, N ); }
public:
Bitmap ( int n = 8 ) {
init ( n ); } //按指定或默认规模创建比特图(为测试暂时选用较小的默认值)
Bitmap ( char* file, int n = 8 ) //按指定或默认规模,从指定文件中读取比特图
{
init ( n ); FILE* fp = fopen ( file, "r" ); fread ( M, sizeof ( char ), N, fp ); fclose ( fp ); }
~Bitmap() {
delete [] M; M = NULL; } //析构时释放比特图空间
void set ( int k ) {
expand ( k ); M[k >> 3] |= ( 0x80 >> ( k & 0x07 ) ); }
void clear ( int k ) {
expand ( k ); M[k >> 3] &= ~ ( 0x80 >> ( k & 0x07 ) ); }
bool test ( int k ) {
expand ( k ); return M[k >> 3] & ( 0x80 >> ( k & 0x07 ) ); }
void dump ( char* file ) //将位图整体导出至指定的文件,以便对此后的新位图批量初始化
{
FILE* fp = fopen ( file, "w" ); fwrite ( M, sizeof ( char ), N, fp ); fclose ( fp ); }
char* bits2string ( int n ) {
//将前n位转换为字符串——
expand ( n - 1 ); //此时可能被访问的最高位为bitmap[n - 1]
char* s = new char[n + 1]; s[n] = '\0'; //字符串所占空间,由上层调用者负责释放
for ( int i = 0; i < n; i++ ) s[i] = test ( i ) ? '1' : '0';
return s; //返回字符串位置
}
void expand ( int k ) {
//若被访问的Bitmap[k]已出界,则需扩容
if ( k