⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 哈希表dhn.txt

📁 完成哈希表的建立
💻 TXT
字号:
#include<iostream>
#include<string>
#define length 45
#define p 43
using namespace std;

struct information{
	string name;
	string number;
	char sex;
	int age;
};



int numberlize(string name){//将名字信息转化成数字信息,即将每个字母的ASCII码值相加
    
	int i=0,sum=0;
	while(name[i]!='\0'){

		sum+=name[i];
		i++;
	}
	return(sum);//返回数字信息处理
}

int hash(int a)//根据名字的数字化信息找其相对应的哈希地址
{
	return(a%p);//返回哈希地址
}

void create(information Hash[],int n){
    //创建哈希表
	information in;
	int a,b,hi;
	for(int i=0;i<n;i++)
	{
		cout<<"Please input the information:name-number-sex-age"<<endl;
		cin>>in.name>>in.number>>in.sex>>in.age;//输入要记录的人的信息
		a=numberlize(in.name);//将所要记录的人的名字数字化
		b=hash(a);//找到哈希地址
		if(Hash[b].name=="noname")
		{//如果所得到的哈希地址是空的,就将索要记录的人放在此位置
			Hash[b]=in;
		}
		else
		{//如果所得到的哈希地址不是空的,就按除留余数法找空位置,即解决冲突.
			for(int j=0;j<length;j++)
			{
				hi=(b+j)%length;
				if(Hash[hi].name=="noname"){
					Hash[b]=in;
					break;
				}

			}

		}
	}
}


void fill(information Hash[])
{//初始化哈希表
	for(int i=0;i<length;i++)
	{
		Hash[i].name="noname";
		Hash[i].number="0";
		Hash[i].age=0;
		Hash[i].sex='x';
	}
}



void Print(information Hash[],int n){//打印函数.

	cout<<Hash[n].name<<"-"<<Hash[n].number<<"-"<<Hash[n].sex<<"-"<<Hash[n].age<<"-"<<endl;
}


void search(information Hash[],string name)
{//在哈希表中查找.
    int n,hi;
	n=hash(numberlize(name));//将名字数字化,并返回哈希地址
	if(Hash[n].name==name) 
		           Print(Hash,n);//打印所找到的人的信息.
	else if(Hash[n].name=="noname"){
		cout<<"There is no the one you find"<<endl;
	}
    else 
		for(int i=0;i<length;i++)
		{//除留余数法解决冲突.
			hi=(n+i)%length;
            if(Hash[hi].name=="noname")
			cout<<"There is no the one you find"<<endl;
			else if(Hash[hi].name==name)
			{
				cout<<Hash[n].name;
				break;
			}
		}
} 


void main() 
{   int n,flag=1,make;
    string a;
    information Hash[length];//定义哈希表.
    fill(Hash);//初始化哈希表.
    cout<<"Please input the entire number"<<endl;
	cin>>n;
    create(Hash,n);//创建哈希表
	while(make){
		cout<<"If you want to start the system,press 1,or 0"<<endl;
		cin>>make;
	while(flag)
	{//循环查找. 
		cout<<"Please input the name of the person you plan to find"<<endl;
		cin>>a;//输入要找的人的名字
	 	search(Hash,a);
		cout<<"if you want to continue,press 1,or 0 "<<endl;
		cin>>flag;
	}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -