百度一面 手写hash

该博客展示了如何使用C++实现一个简单的哈希表,包括插入、删除和搜索功能。哈希函数通过字符串的字符求和取模实现,保证了元素在数组中的分布。在主函数中,创建了一个哈希表实例并进行插入、删除操作,然后输出了哈希表的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值