我被困住了。我正在学习C,有这样的问题:
如何使用字符串数组作为查找表?
我有一个“键”列表:
"A", "A#", "B", "Bb", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"
Run Code Online (Sandbox Code Playgroud)
每个都将引用一个特定的 int“值”(这不是唯一的)。例如"A" -> 9, "A#" -> 10,"Bb" -> 10
我找到了一个答案(在 c 中存储已知的键/值对),当它说“我会...建议仅使用字符串数组作为查找表”时,我认为它为我指明了正确的方向。
但我不知道如何实际实现字符串数组作为查找表?
由于您打算使用字符串作为具有整数值的键,因此最好使用 astruct来包含这样的对。然后建立一个表格。最后,由于您已经小心地保持键的排序顺序,因此您可以使用 C 库函数bsearch进行查找:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct pair {
char *key;
int value;
} PAIR;
// Key strings must be in strcmp() sorted order!
PAIR table[] = {
{"A", 9}, {"A#", 10}, {"B", 11}, {"Bb", 10}, {"C", 11}, {"C#", 12}, {"D", 13},
{"D#", 14}, {"E", 15}, {"F", 16}, {"F#", 17}, {"G", 18}, {"G#", 19},
};
static int compare_keys(const void *va, const void *vb) {
const PAIR *a = va, *b = vb;
return strcmp(a->key, b->key);
}
int get_value(char *key) {
PAIR key_pair[1] = {{key}};
PAIR *pair = bsearch(key_pair, table,
sizeof table / sizeof table[0], sizeof table[0], compare_keys);
return pair ? pair->value : -1;
}
int main(void) {
// Partial test: verify we can look up all the valid keys.
for (int i = 0; i < sizeof table / sizeof table[0]; ++i) {
int value = get_value(table[i].key);
printf("%s -> %d\n", table[i].key, value);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)