glib庫中的哈希函數和比較函數
最近在項目中需要用到哈希表,要以ip地址構造哈希函數和比較函數。就去網上找了下相關的資料,看了下glib中哈希表中的實現方式,雖然最終沒用這個,但既然找了就順便記錄下來,方便查閱。
哈希表是一種提供key-value訪問的數據結構,通過指定的key值可以快速的訪問到與它相關聯的value值。hash表的一種典型用法就是字典,通過單詞的首字母能夠快速的找到單詞。關于哈希表的詳細介紹請查閱數據結構的相關書籍,我這里只介紹glib庫中哈希表的哈希函數和比較函數。
主要包括針對int, int64, double, string四種數據類型的處理。詳細請看下面的代碼。
typedef char gchar;
typedef short gshort;
typedef long glong;
typedef int gint;
typedef gint gboolean;
typedef unsigned char guchar;
typedef unsigned short gushort;
typedef unsigned long gulong;
typedef unsigned int guint;
typedef float gfloat;
typedef double gdouble;
/* Define min and max constants for the fixed size numerical types */
#define G_MININT8 ((gint8) 0x80)
#define G_MAXINT8 ((gint8) 0x7f)
#define G_MAXUINT8 ((guint8) 0xff)
#define G_MININT16 ((gint16) 0x8000)
#define G_MAXINT16 ((gint16) 0x7fff)
#define G_MAXUINT16 ((guint16) 0xffff)
#define G_MININT32 ((gint32) 0x80000000)
#define G_MAXINT32 ((gint32) 0x7fffffff)
#define G_MAXUINT32 ((guint32) 0xffffffff)
#define G_MININT64 ((gint64) G_GINT64_CONSTANT(0x8000000000000000))
#define G_MAXINT64 G_GINT64_CONSTANT(0x7fffffffffffffff)
#define G_MAXUINT64 G_GINT64_CONSTANT(0xffffffffffffffffU)
typedef void* gpointer;
typedef const void *gconstpointer;
gboolean
g_int_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const gint*) v1) == *((const gint*) v2);
}
guint
g_int_hash (gconstpointer v)
{
return *(const gint*) v;
}
gboolean
g_int64_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const gint64*) v1) == *((const gint64*) v2);
}
guint
g_int64_hash (gconstpointer v)
{
return (guint) *(const gint64*) v;
}
gboolean
g_double_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const gdouble*) v1) == *((const gdouble*) v2);
}
guint
g_double_hash (gconstpointer v)
{
return (guint) *(const gdouble*) v;
}
gboolean
g_str_equal (gconstpointer v1,
gconstpointer v2)
{
const gchar *string1 = v1;
const gchar *string2 = v2;
return strcmp (string1, string2) == 0;
}
guint
g_str_hash (gconstpointer v)
{
/* 31 bit hash function */
const signed char *p = v;
guint32 h = *p;
if (h)
for (p += 1; *p != '\0'; p++)
h = (h << 5) - h + *p;
return h;
}
posted on 2010-07-06 17:43
水 閱讀(3842)
評論(1) 編輯 收藏 引用 所屬分類:
c/c++基礎知識