java模拟单队列

2018NOIP集训-5 货物运输(倍增)

  返回  

百度一面 手写hash

2021/8/21 9:39:21 浏览:
#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;
}

 

联系我们

如果您对我们的服务有兴趣,请及时和我们联系!

服务热线:18288888888
座机:18288888888
传真:
邮箱:888888@qq.com
地址:郑州市文化路红专路93号