【问题标题】:Search HashTable not by unique key不按唯一键搜索 HashTable
【发布时间】: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


【解决方案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)));

无论如何,看起来您想要一个三个数据值作为键(键、字段1 和字段2),所以您需要另一种方式来存储您的键,因为 GHashTable 只使用一个参数作为键...

可能是一个包含三个值的字符串键,用“|”之类的字符串分隔(即“0|1|2”),在哈希相等函数中解析数据。

希望对您有所帮助。

【讨论】:

  • 或者我遗漏了什么,你能写下你的“g_hash_table_new”代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2013-11-23
  • 1970-01-01
相关资源
最近更新 更多