c - 不按唯一键搜索哈希表

标签 c data-structures hashtable glib

我有一个包含一个键和一个整数的结构:

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/

相关文章:

c - C 中的段错误(代码转储)错误

java - 相同的代码在 C 和 Java 中给出了不同的答案,你能帮我吗?

c - float 在 c 中打印出负 0

c# - 检查对象列表中的属性是否匹配的最快数据结构

python - 用于在 mp3 播放器中实现歌曲搜索功能的数据结构?

common-lisp - 如何检查散列表中的每个值是否满足 Common Lisp 中的谓词

c - scanf 不存储我的总和

javascript - 数据局部性在 JavaScript 中重要吗?

c - C中哈希表的bucket可以存储什么

c - C语言将二进制文件读入HashTable