C语言宏定义实现的代码,类似uthash
时间: 2024-03-16 19:41:11 浏览: 70
C语言宏定义
以下是一个使用 C 语言宏定义实现的哈希表(类似于 uthash)的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义哈希表结构体 */
#define HASH_TABLE(name, key_type, value_type) \
typedef struct name##_entry { \
key_type key; \
value_type value; \
struct name##_entry *next; \
} name##_entry; \
typedef struct { \
int size; \
name##_entry **table; \
} name
/* 初始化哈希表 */
#define HASH_TABLE_INIT(table, size) \
do { \
(table)->size = size; \
(table)->table = calloc(size, sizeof(*(table)->table)); \
} while (0)
/* 释放哈希表 */
#define HASH_TABLE_FREE(table) \
do { \
int i; \
for (i = 0; i < (table)->size; i++) { \
name##_entry *entry = (table)->table[i]; \
while (entry) { \
name##_entry *next = entry->next; \
free(entry); \
entry = next; \
} \
} \
free((table)->table); \
} while (0)
/* 查找键对应的值 */
#define HASH_TABLE_GET(table, key, default) \
({ \
int index = (key) % (table)->size; \
name##_entry *entry = (table)->table[index]; \
while (entry) { \
if ((entry)->key == (key)) { \
break; \
} \
entry = entry->next; \
} \
(entry) ? (entry)->value : (default); \
})
/* 设置键对应的值 */
#define HASH_TABLE_SET(table, key, value) \
do { \
int index = (key) % (table)->size; \
name##_entry *entry = (table)->table[index]; \
while (entry) { \
if ((entry)->key == (key)) { \
(entry)->value = (value); \
break; \
} \
entry = entry->next; \
} \
if (!entry) { \
entry = calloc(1, sizeof(*entry)); \
entry->key = (key); \
entry->value = (value); \
entry->next = (table)->table[index]; \
(table)->table[index] = entry; \
} \
} while (0)
/* 删除键对应的值 */
#define HASH_TABLE_DEL(table, key) \
do { \
int index = (key) % (table)->size; \
name##_entry *entry = (table)->table[index]; \
name##_entry *prev = NULL; \
while (entry) { \
if ((entry)->key == (key)) { \
if (prev) { \
prev->next = entry->next; \
} else { \
(table)->table[index] = entry->next; \
} \
free(entry); \
break; \
} \
prev = entry; \
entry = entry->next; \
} \
} while (0)
/* 示例用法 */
HASH_TABLE(my_hash_table, int, char *);
int main() {
my_hash_table table;
HASH_TABLE_INIT(&table, 10);
HASH_TABLE_SET(&table, 1, "one");
HASH_TABLE_SET(&table, 2, "two");
HASH_TABLE_SET(&table, 3, "three");
printf("%s\n", HASH_TABLE_GET(&table, 1, "not found"));
printf("%s\n", HASH_TABLE_GET(&table, 2, "not found"));
printf("%s\n", HASH_TABLE_GET(&table, 3, "not found"));
HASH_TABLE_DEL(&table, 2);
printf("%s\n", HASH_TABLE_GET(&table, 1, "not found"));
printf("%s\n", HASH_TABLE_GET(&table, 2, "not found"));
printf("%s\n", HASH_TABLE_GET(&table, 3, "not found"));
HASH_TABLE_FREE(&table);
return 0;
}
```
这个示例代码定义了一个名为 `my_hash_table` 的哈希表类型,其中键的类型为 `int`,值的类型为 `char *`。通过使用宏定义来实现,可以方便地在其他代码中使用这个哈希表类型,并调用宏定义中定义的函数来操作哈希表。
阅读全文