hash表c++实现

hashtable.h

#pragma once
#ifndef _HASHTABLE_H
#define _HASHTABLE_H

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

class hashtable
{
	//out是对ostream对象的引用, 在该对象上将产生输出, ostream为非const, 因为写入到流会改变流的状态
	friend ostream& operator<<(ostream &out, const hashtable& h);
public:
	//向哈希表中插入元素
	void insert(int key, string s);
	//计算要插入的位置
	int hashfunction(string s);
	//删除哈希表中指定的元素
	bool del(string s);
	//搜索hash表中的元素
	int search(string s);
private:
	vector<pair<int, string>> table[20]; //一共二十个格子
};

#endif // !_HASHTABLE_h

hash.cpp

#include "hashtable.h"


ostream& operator<<(ostream &out, const hashtable& h)
{
	for (int i = 0; i < 20; ++i)
	{
		for (int j = 0; j < h.table[i].size(); ++i)
		{
			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> temp;
	temp.first = key;
	temp.second = s;
	int index = hashfunction(s);
	table[index].push_back(temp);
}
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 << "find not" << s << "  in hash" << endl;
	return -1;
}

 main.cpp

#include "hashtable.h"

using namespace std;

int main()
{
	hashtable h;
	h.insert(2, "bob");
	h.insert(3, "abs");
	h.del("bob");
	cout << h;
	cout << h.hashfunction("bob") << endl;
	cout << h.search("abs");
	getchar();
}

猜你喜欢

转载自blog.csdn.net/qq_29869043/article/details/82833378
今日推荐