const int TABLE_LEN = 11;//表的长度 int main(){ vector<string> a({"D","BA","TN","M","CI","I","K","X","TA"}); vector<string> h(11,""); int total = a.size();//total:总的查找次数,每个变量至少查找一次,所以至少为a.size() for(auto it=a.begin();it!=a.end();it++) { char c = (*it)[0]; int index = (c - 'A')%TABLE_LEN; while(!h[index].empty()) { index = index+1>=TABLE_LEN?0:index+1;//注意,index有可能超出h的边界,这时回到h.begin() total++; } h[index] = *it; } //输出hash表 for(int i=0;i<h.size();i++) std::cout<<(h[i].empty()?"空":h[i])<<" "; std::cout<<std::endl; //输出平均查找次数 std::cout<<total<<"/"<<a.size(); }
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
K(7) | TA(9) | BA(2) | M(4) | D(1) | CI(5) | X(8) | | | TN(3) | I(6) |