c语言

c语言字典数据结构是什么

小亿
131
2024-02-05 12:48:47
栏目: 编程语言

C语言没有内置的字典数据结构,但可以使用其他数据结构来实现字典,比如数组、链表或哈希表。以下是使用哈希表实现字典的一种常见方式:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 100

typedef struct {
    char key[50];
    char value[50];
} KeyValuePair;

typedef struct {
    KeyValuePair data[MAX_SIZE];
    int count;
} Dictionary;

void initialize(Dictionary* dictionary) {
    dictionary->count = 0;
}

void insert(Dictionary* dictionary, const char* key, const char* value) {
    if (dictionary->count >= MAX_SIZE) {
        printf("Dictionary is full.\n");
        return;
    }

    strcpy(dictionary->data[dictionary->count].key, key);
    strcpy(dictionary->data[dictionary->count].value, value);
    dictionary->count++;
}

const char* find(Dictionary* dictionary, const char* key) {
    for (int i = 0; i < dictionary->count; i++) {
        if (strcmp(dictionary->data[i].key, key) == 0) {
            return dictionary->data[i].value;
        }
    }

    return NULL;
}

int main() {
    Dictionary dictionary;
    initialize(&dictionary);

    insert(&dictionary, "apple", "果实");
    insert(&dictionary, "banana", "香蕉");
    insert(&dictionary, "cherry", "樱桃");

    const char* value = find(&dictionary, "banana");
    if (value) {
        printf("The Chinese meaning of 'banana' is '%s'\n", value);
    } else {
        printf("Cannot find the word 'banana'\n");
    }

    return 0;
}

该示例演示了使用哈希表实现的简单字典数据结构。Dictionary 结构包含一个 KeyValuePair 数组,用于存储键值对。通过 insert 函数可以向字典中插入新的键值对,通过 find 函数可以查找指定键的值。

0
看了该问题的人还看了