Hash Algorithm

#include <cstring>
#include <iostream>

template <class T>
class HashTable {
#ifndef HASH_K
#define HASH_K 100007
#endif
private:
	struct {
		int key;
		T value;
		bool used;
	} hashTable[HASH_K];
public:
	HashTable() {
		memset(hashTable, 0, sizeof(hashTable));
	}
	
	T &operator [] (const int &k) {
		int h = k % HASH_K;
		
		for (int i = 0; i < HASH_K; i++) {
			int hh = (h + i) % HASH_K;
			if (hashTable[hh].key == k || hashTable[hh].used == false) {
				hashTable[hh].used = true;
				hashTable[hh].key = k;
				return hashTable[hh].value;
			}
		}
	}
};

HashTable<int> ht;

int main() {
	using namespace std;

	ht[1] = 2;
	ht[3] = 5;
	ht[100008] = 233;
	
	cout << ht[1] << " " << ht[2] << " " << ht[100008] << endl;
	return 0;
}

One thought on “Hash Algorithm

Leave a Reply to xc Cancel reply

Your email address will not be published. Required fields are marked *