首页 文章

不使用唯一键搜索HashTable

提问于
浏览
0

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

struct MyStruct
{
guint32 key;
guint64 field1;
guint64 field2
guint64 field3;
};

我需要存储到某种dictionarty结构中 . 我选择了一个GHashTable(glib) .

MyStruct成员密钥是唯一的,因此我选择使用它作为密钥 . 但是我需要通过在field1上搜索来检索每个struct实例,并且可能在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中直接访问的其他选项是什么?

1 回答

  • 1

    首先,你得到一个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”),解析散列等于函数中的数据 .

    希望它有所帮助 .

相关问题