C言語で辞書を作成する方法
C言語では辞書というデータ構造が標準では提供されていませんが、構造体を自分で定義して連結リストを用いることで辞書のような機能を実現することができます。以下にその簡単な実装例を示します。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义字典节点结构体
typedef struct Node {
char key[50]; // 键
int value; // 值
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建新节点
Node* createNode(char* key, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->key, key);
newNode->value = value;
newNode->next = NULL;
return newNode;
}
// 向字典中插入键值对
void insert(Node** dictionary, char* key, int value) {
Node* newNode = createNode(key, value);
newNode->next = *dictionary;
*dictionary = newNode;
}
// 从字典中查找键对应的值
int find(Node* dictionary, char* key) {
Node* cur = dictionary;
while (cur != NULL) {
if (strcmp(cur->key, key) == 0) {
return cur->value;
}
cur = cur->next;
}
return -1; // 键不存在时返回-1
}
int main() {
Node* dictionary = NULL; // 初始化字典为空
// 向字典中插入键值对
insert(&dictionary, "apple", 1);
insert(&dictionary, "banana", 2);
insert(&dictionary, "orange", 3);
// 从字典中查找键对应的值
int value = find(dictionary, "banana");
if (value != -1) {
printf("Value: %d\n", value);
} else {
printf("Key not found.\n");
}
return 0;
}
連想配列を作成する簡単なコードで、キーと値のペアを格納する連結リストを使用します。 insert 関数を使用して連想配列にキーと値のペアを挿入し、 find 関数を使用して連想配列からキーに対応する値を検索できます。メイン関数では、この連想配列を使用する方法を示しています。