溫馨提示×

c語言字典數(shù)據(jù)結(jié)構(gòu)是什么

小億
126
2024-02-05 12:48:47
欄目: 編程語言

C語言沒有內(nèi)置的字典數(shù)據(jù)結(jié)構(gòu),但可以使用其他數(shù)據(jù)結(jié)構(gòu)來實(shí)現(xiàn)字典,比如數(shù)組、鏈表或哈希表。以下是使用哈希表實(shí)現(xiàn)字典的一種常見方式:

#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", "果實(shí)");
    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;
}

該示例演示了使用哈希表實(shí)現(xiàn)的簡單字典數(shù)據(jù)結(jié)構(gòu)。Dictionary 結(jié)構(gòu)包含一個(gè) KeyValuePair 數(shù)組,用于存儲鍵值對。通過 insert 函數(shù)可以向字典中插入新的鍵值對,通過 find 函數(shù)可以查找指定鍵的值。

0