帮我写一个C++ HashMap的代码
时间: 2024-05-12 07:20:20 浏览: 123
以下是一个C语言实现的HashMap的简单示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct Node {
char* key;
char* value;
struct Node* next;
} Node;
typedef struct {
Node* head;
} Bucket;
typedef struct {
Bucket* buckets;
} HashMap;
int hash(char* key) {
int hash = 0;
int len = strlen(key);
for (int i = 0; i < len; i++) {
hash += key[i];
}
return hash % TABLE_SIZE;
}
Node* create_node(char* key, char* value) {
Node* node = (Node*) malloc(sizeof(Node));
node->key = key;
node->value = value;
node->next = NULL;
return node;
}
void insert(HashMap* map, char* key, char* value) {
int index = hash(key);
Node* node = create_node(key, value);
if (map->buckets[index].head == NULL) {
map->buckets[index].head = node;
} else {
Node* cur = map->buckets[index].head;
while (cur->next) {
cur = cur->next;
}
cur->next = node;
}
}
char* search(HashMap* map, char* key) {
int index = hash(key);
Node* cur = map->buckets[index].head;
while (cur) {
if (strcmp(cur->key, key) == 0) {
return cur->value;
}
cur = cur->next;
}
return NULL;
}
void destroy_map(HashMap* map) {
for (int i = 0; i < TABLE_SIZE; i++) {
Node* cur = map->buckets[i].head;
while (cur) {
Node* temp = cur;
cur = cur->next;
free(temp->key);
free(temp->value);
free(temp);
}
}
free(map->buckets);
free(map);
}
int main() {
HashMap* map = (HashMap*) malloc(sizeof(HashMap));
map->buckets = (Bucket*) malloc(sizeof(Bucket) * TABLE_SIZE);
insert(map, "name", "Tom");
insert(map, "age", "18");
insert(map, "gender", "male");
printf("name: %s\n", search(map, "name"));
printf("age: %s\n", search(map, "age"));
printf("gender: %s\n", search(map, "gender"));
destroy_map(map);
return 0;
}
```
这个HashMap使用了链表解决冲突,实现了插入和查找操作。当然,这个实现还可以更完善,比如增加删除操作,缩小哈希表空间等等。
阅读全文