#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class hashtable {
friend ostream& operator<<(ostream &out, const hashtable& h);
public:
void insert(int key, string s);
int hashfunction(string s);
bool del(string s);
int search(string s);
private:
vector<pair<int, string>> table[20];
};
ostream& operator<<(ostream &out, const hashtable& h)
{
for(int i=0; i<20; i++)
{
for(int j=0; j<h.table[i].size(); ++j)
{
out << h.table[i][j].first << " " << h.table[i][j].second;
out << endl;
}
}
return out;
}
void hashtable::insert(int key, string s) {
pair<int, string> tmp;
tmp.first = key;
tmp.second = s;
int index = hashfunction(s);
table[index].push_back(tmp);
}
int hashtable::hashfunction(string s) {
int sum = 0;
for (int i=0; i<s.size(); i++) {
sum+=s[i];
}
return (sum-1) % 20;
}
bool hashtable::del(string s) {
int index = hashfunction(s);
for(int i = 0; i<table[index].size(); i++) {
if(table[index][i].second == s) {
table[index].erase(table[index].begin()+i);
return true;
}
}
cout << s << "not in hash " << endl;
return false;
}
int hashtable::search(string s) {
int index = hashfunction(s);
for (int i = 0; i<table[index].size(); i++) {
if(table[index][i].second == s) {
return table[index][i].first;
}
}
cout << " not find " << s << " in hashtable" << endl;
return -1;
}
int main(int argc, const char * argv[]) {
hashtable h;
h.insert(1, "abc");
h.insert(2, "def");
h.insert(3, "ghi");
cout << h << endl;
h.del("def");
cout << h << endl;
cout << h.hashfunction("def") << endl;
cout << h.search("abc") << endl;
return 0;
}