以下是一个简单的例子,用于说明如何使用查找表实现查找:

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

#define MAX_ITEMS 100 // 最大数据项数

typedef struct { int key1; // 主关键字 char key2[21]; // 次关键字 // 其他数据项... } Item;

typedef struct { Item items[MAX_ITEMS]; int count; } Table;

// 初始化查找表 void initTable(Table *t) { t->count = 0; }

// 向查找表中插入一个数据项 void insert(Table *t, int key1, const char key2 /, 其他数据项... */) { if (t->count >= MAX_ITEMS) { printf("Error: table is full\n"); exit(EXIT_FAILURE); } t->items[t->count].key1 = key1; strncpy(t->items[t->count].key2, key2, 20); t->count++; }

// 根据主关键字查找数据项 int searchByKey1(const Table *t, int key1, int *index) { int i; for (i = 0; i < t->count; i++) { if (t->items[i].key1 == key1) { *index = i; // 找到了,返回下标 return 1; } } // 没找到 *index = -1; return 0; }

// 根据主关键字和次关键字查找数据项 int search(const Table *t, int key1, const char *key2, Item *result) { int i, index; if (!searchByKey1(t, key1, &index)) { // 没找到 return 0; } // 找到了,检查次关键字是否匹配 for (i = index; i < t->count && t->items[i].key1 == key1; i++) { if (strcmp(t->items[i].key2, key2) == 0) { // 匹配,返回结果 *result = t->items[i]; return 1; } } // 次关键字不匹配 return 0; }

int main() { Table t; Item result;

// 初始化查找表
initTable(&t);

// 向查找表中插入数据项
insert(&t, 1, "a");
insert(&t, 2, "b");
insert(&t, 3, "c");
insert(&t, 1, "d");
insert(&t, 2, "e");
insert(&t, 3, "f");

// 根据主关键字查找
int index;
if (searchByKey1(&t, 2, &index)) {
    printf("Found at index %d\n", index);
} else {
    printf("Not found\n");
}

// 根据主关键字和次关键字查找
if (search(&t, 1, "d", &result)) {
    printf("Found: %d %s\n", result.key1, result.key2);
} else {
    printf("Not found\n");
}

return 0;

原文地址: https://www.cveoy.top/t/topic/fQ18 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录