?? 哈希表gai.cpp
字號:
#include <iostream>
#include<string>
#include<fstream>
#define m 5 //表長
#define y 3 //小于等于mde 最大素數
//#define NULLKEY #
//代表空記錄的關鍵字值
using namespace std;
typedef struct
{
string name;
string sex;
int age;
}RecordType;
typedef RecordType HashTable[m];
//哈希查找函數
int HashSearch(HashTable ht,string K)
{
int h0,hi;
h0=(K[0]-96)%y;
if(ht[h0].name=="#")
{
return(-1);
}
else
{
if(ht[h0].name==K)
{
return(h0);
}
else
{
for(int i=1;i<=m-1;i++)
{
hi=(h0+i)%m;
if(ht[hi].name=="#")
{
return(-1);
}
else
{
if(ht[hi].name==K)
{
return(hi);
}
}
}
return (-1);
}
}
}
//創建哈希表
void HashCreate(HashTable & ht)
{
//將文件中信息讀出
ifstream in("hash.txt");
string s,t;
int ia,h0,hi;
RecordType p;
for(int i=0;i<3&&s!="#";i++)
{
in>>s>>t>>ia;
// if(s="#")break;
p.name=s;
p.sex=t;
p.age=ia;
h0=(s[0]-96)%y;//哈希函數
if(ht[h0].name=="#")
{
ht[h0]=p;
}
else
{
for(int i=0;i<=m-1;i++)
{
hi=(h0+i)%m;
if(ht[hi].name=="#")
{
ht[hi]=p;
break; //注意此處
}
}
}
}
}
//打印哈希表
void HashPrint(HashTable ht)
{
cout<<"name "<<"sex "<<"age "<<endl;
for(int i=0;i<m;i++)
{
if(ht[i].name!="#")
cout<<ht[i].name<<" "<<ht[i].sex<<" "<<ht[i].age<<endl;
else
cout<<"空元素"<<endl;
}
}
void main()
{
RecordType hata[m];
//初始化哈希表
for(int i=0;i<m;i++)
{
hata[i].name="#";
}
// HashPrint(hata);
HashCreate(hata);
cout<<"輸出創建好的哈希表:"<<endl;
HashPrint(hata);
//查找元素
cout<<"輸入要查找的姓名:"<<endl;
string str;
cin>>str;
int t=HashSearch(hata,str);
if(t!=-1)
{
cout<<"查找成功!"<<endl;
cout<<hata[t].name<<" "<<hata[t].sex<<" "<<hata[t].age<<endl;
}
else
{
cout<<"查找失敗!"<<endl;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -