在编程中,字典(Dictionary)是一种非常常用的数据结构,它允许我们通过“键”快速查找对应的“值”。虽然 C 语言本身没有内置的字典类型(不像 Python 的 dict 或 JavaScript 的对象),但我们可以通过自己实现一个基于哈希表(Hash Table)的字典结构。本教程将从零开始,详细讲解如何用 C 语言实现一个简单的字典,并确保即使是编程新手也能理解。
字典是一种键值对(Key-Value Pair)集合。例如,你可以用它来存储“姓名 → 年龄”这样的映射关系:
理想情况下,插入、查找和删除操作的时间复杂度应接近 O(1)。为了达到这个目标,我们通常使用哈希表作为底层实现。
我们将构建一个简单的哈希表,包含以下组件:
下面是一个完整的、可运行的 C 语言字典实现:
#include <stdio.h>#include <stdlib.h>#include <string.h>// 定义字典项结构体typedef struct DictItem { char* key; int value; struct DictItem* next;} DictItem;// 定义字典结构体typedef struct Dictionary { DictItem** buckets; int size;} Dictionary;// 哈希函数:将字符串转为索引unsigned int hash(const char* key, int table_size) { unsigned int hash_value = 0; while (*key) { hash_value = (hash_value << 5) + *key++; } return hash_value % table_size;}// 创建新字典Dictionary* create_dict(int size) { Dictionary* dict = (Dictionary*)malloc(sizeof(Dictionary)); dict->buckets = (DictItem**)calloc(size, sizeof(DictItem*)); dict->size = size; return dict;}// 插入键值对void dict_set(Dictionary* dict, const char* key, int value) { unsigned int index = hash(key, dict->size); DictItem* item = dict->buckets[index]; // 检查是否已存在该键 while (item) { if (strcmp(item->key, key) == 0) { item->value = value; // 更新值 return; } item = item->next; } // 创建新项并插入链表头部 DictItem* new_item = (DictItem*)malloc(sizeof(DictItem)); new_item->key = strdup(key); new_item->value = value; new_item->next = dict->buckets[index]; dict->buckets[index] = new_item;}// 获取值int dict_get(Dictionary* dict, const char* key, int default_value) { unsigned int index = hash(key, dict->size); DictItem* item = dict->buckets[index]; while (item) { if (strcmp(item->key, key) == 0) { return item->value; } item = item->next; } return default_value; // 未找到返回默认值}// 主函数测试int main() { Dictionary* my_dict = create_dict(10); dict_set(my_dict, "张三", 25); dict_set(my_dict, "李四", 30); dict_set(my_dict, "王五", 28); printf("张三年龄:%d\n", dict_get(my_dict, "张三", -1)); printf("李四年龄:%d\n", dict_get(my_dict, "李四", -1)); printf("赵六年龄:%d(未找到)\n", dict_get(my_dict, "赵六", -1)); // 注意:实际项目中应释放内存 return 0;}
这段代码展示了如何用 C 语言实现一个基础的字典结构:
hash() 函数将字符串键转换为数组索引;dict_set() 负责插入或更新键值对;dict_get() 根据键查找对应的值;对于更复杂的场景,你可以考虑:
dict_delete();通过本教程,你已经掌握了如何在 C 语言中实现一个简单的字典数据结构。这不仅加深了你对 C语言字典实现 和 C语言哈希表 的理解,也为学习更高级的 数据结构教程 打下基础。即使你是 C语言小白入门 阶段,只要跟着步骤练习,也能轻松掌握这一核心技能。
动手试试吧!修改代码、添加功能,让这个字典真正属于你。
本文由主机测评网于2025-12-16发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025128702.html