#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <glib.h>
#define COUNT
10
struct test
{
int i;
char a[10];
};
struct test arr[COUNT] = {
{0, "0"},
{1, "a"},
{2, "b"},
{3, "c"},
{4, "d"},
{5, "e"},
{6, "f"},
{7, "g"},
{8, "h"},
{9, "j"}
};
void display_user_data(gpointer key, gpointer value, gpointer user_data)
{
printf ("%d => %s \n",
*(int *)key, (char *)value);
}
gboolean test_user_data(gpointer
key, gpointer value, gpointer user_data)
{
printf ("%d => %s \n",
*(int *)key, (char *)value);
return 1;
}
int main()
{
int i;
GHashTable *hash;
hash =
g_hash_table_new(g_int_hash, g_int_equal);
printf ("create a hash table %p. %m \n", hash);
for (i=0; i<COUNT-3; i++)
g_hash_table_insert(hash, (gpointer)&arr[i].i, (gpointer)&arr[i].a);
int j=2;
g_hash_table_insert(hash, (gpointer)&j, (gpointer)"aaaaaaaaaaaaaaa");
printf ("insert key=>value to a hash. %m \n");
printf ("hash size = %d \n",
g_hash_table_size(hash));
g_hash_table_foreach(hash, display_user_data, NULL);
printf ("#############################\n");
/*
test_user_data((gpointer)&arr[2].i, (gpointer)&arr[2].a,
NULL);
printf ("%p \n", g_hash_table_find(hash, test_user_data, NULL));
*/
for (i=0; i<COUNT; i++)
printf ("%d => %s \n",
arr[i].i, (char *)g_hash_table_lookup(hash, (gpointer)&arr[i].i));
int k=1;
printf ("%d => %s \n",
k, (char
*)g_hash_table_lookup(hash, (gpointer)&k));
printf ("g_hash_table_foreach_remove #############################\n");
g_hash_table_foreach_remove(hash, test_user_data, NULL);
printf ("hash size = %d \n",
g_hash_table_size(hash));
return 0;
}
|