C++用类实现字符串哈希查找的功能

本文章部分引用了这两篇博客,总结的很好,可以看看:
https://blog.csdn.net/wanglx_/article/details/40300363
https://blog.csdn.net/lcalqf/article/details/60775221

由于哈希查找是利用哈希函数求出哈希值来直接的找到数据,使得哈希查找的时间复杂度为O(1),随着数据量的增大,时间也主要是浪费在求哈希值时解决访问冲突的上面。

为了使每一个字符都对最后的哈希值产生影响这个例子采用的是BKDRHash算法的哈希函数,拉链法解决的哈希冲突,环境是Ubuntu 16.04 Linux系统

  • CHashmap.h:
#pragma once

#include 
#include 
#include 


typedef struct node{

    char *name;//字段名

    char *desc;//描述

    struct node *next;

}node;

 

#define HASHSIZE 50001 //hash表长度,长度选择的好能够很好的减少哈希冲突

class CHashmap
{
public:
	CHashmap();
	~CHashmap();

public:
	node* hashtable[HASHSIZE];//定义一个hash数组,该数组的每个元素是一个hash结点指针
	unsigned int BKDRHash(char *str);//	BKDRHash算法求哈希值

	node* lookup(char *str);//通过name找到其对应的结点

	char* search(char* name);//通过name找到desc值

	node* malloc_node(char* name, char* desc);//插入字符串时申请堆的函数

	int insert(char* name, char* desc);//哈希表插入字符串

	void displayHashTable();//展示哈希表
 
	void cleanUp();//清除哈希表

};

  • CHashmap.cpp:

#include "CHashmap.h"


CHashmap::CHashmap()
{

	bzero(hashtable,sizeof(hashtable));

}
CHashmap::~CHashmap()
{

	cleanUp();

}


//拉链法实现


unsigned int CHashmap::BKDRHash(char *str)

{

    unsigned int seed = 131; // 31 131 1313 13131 131313 etc..此类质素效果比较好

    unsigned int hash = 0;

 
    while (*str)

    {

        hash = hash * seed + (*str++);

    }

 

    return ((hash & 0x7FFFFFFF)%HASHSIZE);

}

 

node* CHashmap::lookup(char *str)

{

    unsigned int hashvalue = BKDRHash(str);

    node* np = hashtable[hashvalue];

    for( ; np!=NULL; np = np->next)

    {//这里是链地址法解决的冲突,返回的是第一个链表结点

        if(!strcmp(np->name, str))//strcmp相等的时候才返回0

            return np;

    }

    return NULL;

}

 

char* CHashmap::search(char* name)

{//对hash表查找特定元素(元素是字符串)

    node* np=lookup(name);

    if(np==NULL)

        return NULL;

    else

        return np->desc;

}

 

node* CHashmap::malloc_node(char* name, char* desc)

{//在堆上为结点分配内存,并填充结点

    node *np=(node*)malloc(sizeof(node));

    if(np == NULL)

        return NULL;


    np->name=(char*)malloc((strlen(name)+1)*sizeof(char));

    if(np->name == NULL)
    {
		free(np);
        return NULL;

    }
    np->desc=(char*)malloc((strlen(desc)+1)*sizeof(char));

    if(np->desc == NULL)
    {
		free(np);     
		free(np->name);
        return NULL;
    }
	
    strcpy(np->name,name);

    strcpy(np->desc,desc);

    np->next = NULL;

    return np;

}

 

int CHashmap::insert(char* name, char* desc)

{

    unsigned int hashvalue;

    hashvalue = BKDRHash(name);

    //头插法,不管该hash位置有没有其他结点,直接插入结点

    node* np = malloc_node(name, desc);

    if (np == NULL) return 0;//分配结点没有成功,则直接返回

    np->next = hashtable[hashvalue];

    hashtable[hashvalue] = np;

    return 1;

}

 

/* A pretty useless but good debugging function,

which simply displays the hashtable in (key.value) pairs

*/

void CHashmap::displayHashTable()

{//显示hash表所有元素(不包括空)

    node *np;

    unsigned int hashvalue;

    for(int i=0; i < HASHSIZE; ++i)

    {

        if(hashtable[i] != NULL)

        {

            np = hashtable[i];

            printf("\nhashvalue: %d (", i);

            for(; np != NULL; np=np->next)

                printf(" (%s.%s) ", np->name, np->desc);

            printf(")\n");

        }

    }

}

 

void CHashmap::cleanUp()

{//清空hash表

    node *np,*tmp;

    for(int i=0;i < HASHSIZE; ++i)

    {

        if(hashtable[i] != NULL)

        {

            np = hashtable[i];
	  
	    hashtable[i] = NULL;

            while(np != NULL)

            {

                tmp = np->next;

                free(np->name);

                free(np->desc);

                free(np);

                np = tmp;

            }

        }

    }

}
  • main.cpp:

#include
#include "CHashmap.h"

int main()
{

    CHashmap hash;

    char* names[]={"First Name","Last Name","address","phone","k101","k110"};

    char* descs[]={"Kobe","Bryant","USA","26300788","Value1","Value2"};

    

    for(int i=0; i < 6; ++i)
        hash.insert(names[i], descs[i]);

    printf("we should see %s\n",hash.search("k110"));

    hash.insert("phone","9433120451");//这里计算的hash是冲突的,为了测试冲突情况下的插入

     printf("we have %s and %s\n",hash.search("k101"),hash.search("phone"));

    hash.displayHashTable();

    hash.cleanUp();

    return 0;

}

编译命令:
g++ CHashmap.cpp main.cpp
效果:
C++用类实现字符串哈希查找的功能_第1张图片

你可能感兴趣的:(算法)