Chinaunix首页 | 论坛 | 博客
  • 博客访问: 122583
  • 博文数量: 20
  • 博客积分: 1627
  • 博客等级: 上尉
  • 技术积分: 383
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-25 16:11
文章分类

全部博文(20)

文章存档

2012年(5)

2011年(2)

2010年(12)

2009年(1)

我的朋友

分类: C/C++

2010-04-07 18:21:49

glib手册地址
hash.c

#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;
}


makefile

CC=gcc

CFLAGS=-Wall -g

hash: hash.o
        $(CC) $(CFLAGS) -o $@ $< `pkg-config --libs glib-2.0`
hash.o: hash.c
        $(CC) $(CFLAGS) -c $< `pkg-config --cflags glib-2.0`

clean:
        rm -f hash *.o



阅读(889) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~