[C++] HashMap

신남·2025년 2월 28일

hashmap을 직접 구현한 코드입니다.
체이닝 기법으로 충돌을 방지했고, <int, T>의 형태로 만들었습니다.
<int, int>형태로 만들었고, 이후 <int, anytype> <anytype, anytype>형태로 수정하겠습니다. 수정 완료

#define MAX_TABLE 5000
template<typename T>
struct Hash {
	struct HashNode {
		int id;
		T value;
		HashNode* next_h;

		HashNode(int a, T b, HashNode* c):id(a), value(b), next_h(c) {}
		~HashNode() { delete next_h; }
	}*table[MAX_TABLE];


	T get(int key) {
		HashNode* node = table[key % MAX_TABLE];
		while (node) {
			if (node->id == key) {
				return node->value;
			}
			node = node->next_h;
		}

		throw;

	}

	void set(int key, T value) {
		int hash = key % MAX_TABLE;
		HashNode* new_node = new HashNode(key, value, table[hash]);
		table[hash] = new_node;
	}

	void clear() {
		for (int i = 0; i < MAX_TABLE; ++i) {
			delete table[i];
			table[i] = 0;
		}
	}

};

Hash<int> hash;

0개의 댓글