ハッシュテーブル

glibcのハッシュテーブル

#include <search.h>
int hcreate(size_t nel);
ENTRY *hsearch(ENTRY item, ACTION action);
void hdestroy(void);

nelでハッシュテーブルに格納できるデータ数の最大値を設定します。
キーには文字列しか使えません。
hdestroy()を呼ぶとハッシュテーブルだけでなくitem.keyも解放されるので、ハッシュテーブルへ渡す際にはstrdup()を使いましょう。

使い方
#include <search.h>
#include <stdio.h>
#include <string.h>

int main() {
  ENTRY e,*r;

  e.key=strdup("key");
  e.data="value";
  hcreate(11);
  hsearch(e,ENTER);
  r=hsearch(e,FIND);
  printf("%s %s\n",r->key,(char*)r->data);
  hdestroy();
  return 0;
}
コンパイル

プログラムが書かれたファイル名をtest.cとします。

gcc test.c
実行結果
key value

GHashTable

#include <glib.h>
GHashTable* g_hash_table_new(GHashFunc hash_func, GEqualFunc key_equal_func);
void g_hash_table_insert(GHashTable *hash_table, gpointer key, gpointer value);
gpointer g_hash_table_lookup(GHashTable *hash_table, gconstpointer key);
void g_hash_table_destroy(GHashTable *hash_table);

GLibに含まれているハッシュテーブルです。挿入されるデータが増えると自動的にテーブルの大きさを拡張します。
g_hash_table_new()ではハッシュ値を生成する関数、キーの比較関数を指定できるので、どんな型もキーに使えます(文字列、整数値、ポインタ用のハッシュ値生成関数と比較関数は予め用意されています)。
また、ハッシュテーブルを操作する関数も豊富にあります。

使い方
#include <glib.h>
#include <stdio.h>

int main() {
  GHashTable *table;
  gpointer r;

  table=g_hash_table_new(g_str_hash,g_str_equal);
  g_hash_table_insert(table,"key","value");
  r=g_hash_table_lookup(table,"key");
  printf("%s\n",(char*)r);
  g_hash_table_destroy(table);
  return 0;
}
コンパイル

プログラムが書かれたファイル名をtest.cとします。

gcc test.c `pkg-config --cflags glib-2.0` `pkg-config --libs glib-2.0`
実行結果
value