【发布时间】:2015-01-29 11:51:11
【问题描述】:
我有一个包含一个键和一个整数的结构体:
struct MyStruct
{
guint32 key;
guint64 field1;
guint64 field2
guint64 field3;
};
我需要将其存储到某种字典结构中。我选择了一个 GHashTable (glib)。
MyStruct 成员键是唯一的,因此我选择使用它作为键。但是,我需要通过在 field1 上进行搜索来检索每个结构实例,并且可能在 field1 和 field2 上进行搜索。
请在下面找到我的哈希和相等函数。
static guint32
my_struct_oid_hash(gconstpointer k)
{
my_struct *my_data = (my_struct *)k;
return my_data->key;
}
static gint
my_struct_oid_equal(gconstpointer k1, gconstpointer k2)
{
my_struct *my_data1;
my_struct *my_data2;
my_data1 = (my_struct *)k1;
my_data2 = (my_struct *)k2;
return ((my_data1->field1 == my_data2->field1) && (my_data1->field2 == my_data2->field2));
}
问题是lookup 和lookup_extenede 函数总是返回NULL。
my_struct* my_key;
my_key->key=0; //set key to 0 just for the sake of inizializazion. It is not used for the comparison in the my_struct_oid_equal function.
my_key->field1=1;
my_key->field2=2;
my_data = ((my_struct*)(g_hash_table_lookup(my_hashtable, my_key)));
我做错了什么?
我把 my_struct_oid_hash 的最后一行改成了
return ((guint32)*((const my_struct *)my_data));
我尝试了here 建议的方法,但出现以下编译错误:
error C2440: 'type cast' : cannot convert from 'const my_struct' to 'guint32'
warning C4033: 'my_struct_oid_hash' must return a value.
但是我不认为这是要走的路,因为将 my_struct 转换为 guint 没有多大意义。
我还认为哈希表可能不是最好的解决方案,因为我没有按键值搜索。在这种情况下,除了 GList,在 glib 中直接访问的其他选项是什么?
【问题讨论】:
-
你考虑过 Boost.MultiIndex 吗?
-
@dmg。我不能用它。我必须使用 glib。这是项目的约束。
-
@geraldCelente 你是如何将这些结构插入哈希表的?
标签: c data-structures hashtable glib