我有一个包含一个键和一个整数的结构:
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 中直接访问的选项?
最佳答案
首先,您得到的是 NULL,因为您正在寻找结构,而不是键。而不是:
my_data = ((my_struct*)(g_hash_table_lookup(my_hashtable, my_key)));
使用
my_data = ((my_struct*)(g_hash_table_lookup(my_hashtable, my_key->key)));
或者
my_data = ((my_struct*)(g_hash_table_lookup(my_hashtable, 0)));
无论如何,看起来你想要一个三个数据值作为键(key、field1和field2),所以你需要另一种方式来存储你的键,因为GHashTable只使用一个参数作为键...
可能是一个包含三个值的字符串键,由“|”之类的字符串分隔(即“0|1|2”),解析哈希等于函数中的数据。
希望有帮助。
关于c - 不按唯一键搜索哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28214069/