c语言hashmap库函数
时间: 2023-09-02 12:05:46 浏览: 49
C语言本身不提供HashMap的库函数,但是可以通过自己编写代码实现HashMap。下面是一个简单的实现:
```c
#include <stdio.h>
#include <string.h>
#define TABLE_SIZE 10000
struct Node {
char* key;
char* value;
struct Node* next;
};
struct Node* table[TABLE_SIZE];
// Hash function
unsigned long hash(char* key) {
unsigned long hash = 5381;
int c;
while (c = *key++) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash % TABLE_SIZE;
}
// Put a key-value pair into the table
void put(char* key, char* value) {
unsigned long index = hash(key);
struct Node* node = table[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
node->value = value;
return;
}
node = node->next;
}
struct Node* new_node = malloc(sizeof(struct Node));
new_node->key = key;
new_node->value = value;
new_node->next = table[index];
table[index] = new_node;
}
// Get the value associated with a key
char* get(char* key) {
unsigned long index = hash(key);
struct Node* node = table[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return NULL;
}
int main() {
put("apple", "red");
put("banana", "yellow");
put("orange", "orange");
printf("The color of apple is %s\n", get("apple"));
printf("The color of banana is %s\n", get("banana"));
printf("The color of orange is %s\n", get("orange"));
return 0;
}
```
这个HashMap使用了开放地址法来处理哈希冲突,链表来保存键值对。可以通过调整`TABLE_SIZE`的大小来改变哈希表的大小。