如何解决如何使用除法和二次探测将 int 存储到哈希表中以避免 C++ 中的冲突
所以最近我有一个关于我的数据结构主题的测验,有一个涉及哈希表的问题。我的讲师确实教过它背后的理论,但从未教过编码它的方法,这非常令人沮丧。我试图用谷歌搜索任何有关如何操作的信息,但无济于事。现在在测验之后,我只想知道这是如何完成的,以便我可以提高我的知识以进行进一步的测试或测验。我还添加了我提交的内容,以防有人需要查看。
#include <iostream>
using namespace std;
int hash[30];
string key;
int value,keylength;
char yesorno;
int division(int keylength){
for(int i = 0; i <= keylength; i++){
value = keylength % 30;
hash[value];
cout << "The bucket/cell location : " << hash[value] << endl;
}
}
/*int hashing(int hash[],int value){
for(int k = 0; k <=30; k++){
hash[k] = value;
cout << "The bucket/cell location : " << hash[value] << endl;
}
}*/
int main(){
do {
cout << "Enter planet name : ";
cin >> key;
keylength == key.length();
division(keylength);
//hashing(hash,value);
cout << "Do you want to continue...? " << endl;
cout << "Press 'Y' or 'y' for Yes else 'N' or 'n' : ";
cin >> yesorno;
} while(yesorno = 'Y' || 'y');
return 0;
}
解决方法
问题不是要求将 int
存储到哈希表中,而是要求存储 key
(此处为行星名称)的哈希表中的位置值。二次探测的实现方式有点像这样:
-
使用除法方法从键创建哈希值
-
如果
hashtable[value]
未被占用,则不需要任何探测。我们占用它并返回值。否则,我们将像这样开始二次探测:for(int i=0;i<30;i++){ probe_value=(i*i+value)%30; // quadratic probing if(hashtable[probe_value] == "0"){ return probe_value; } } return -1; // as hashtabletable is full;
完整的程序代码:
#include<bits/stdc++.h>
using namespace std;
string hashtable[30];
int hashtableing(string key){
int value,probe_value;
value= (key.length())%30; //division
if(hashtable[value] == "0" || hashtable[value] ==key){
hashtable[value]=key;
return value;
}else{
for(int i=0;i<30;i++){
probe_value=(i*i+value)%30; // quadratic probing
if(hashtable[probe_value] == "0"){
return probe_value;
}
}
return -1; // as hashtabletable is full;
}
}
int main(){
string key;
char choice='Y';
for(int i=0;i<30;i++){
hashtable[i]="0"; //0 indicates cell is unoccupied for probing
}
while(choice != 'N' && choice !='n'){
cout<<"Enter planet name:"<<endl;
cin>>key;
cout<<"The bucket/cell location :"<< hashtableing(key)<<endl;
cout<<"Do you want to continue...?"<<endl;
cout<<"Press 'Y' or 'y' for Yes else 'n' or 'N':";
cin>>choice;
}
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。