bsearch()
が提供する関数を使用して、ルックアップ テーブルを簡単に作成できますstdlib.h
。実際の例は次のとおりです。
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define count(ARRAY) (sizeof(ARRAY)/sizeof(*ARRAY))
struct item
{
const char * name;
int value;
};
static _Bool sorted;
static struct item items[] =
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "ten", 10 }
};
static int compare(const void * p1, const void * p2)
{
return strcmp(*((const char **)p1), *((const char **)p2));
}
int get(const char * name)
{
if(!sorted)
{
qsort(items, count(items), sizeof(*items), compare);
sorted = 1;
}
struct item * item = bsearch(&name, items, count(items), sizeof(*items),
compare);
return item ? item->value : 0;
}
int main(int argc, char ** argv)
{
int i;
for(i = 1; i < argc; ++i)
printf("%i\n", get(argv[i]));
return 0;
}