将非 pod 结构插入 GHashTable
我正在尝试构建一个包含 int、time_t 和一些 char* 的结构实例的 GHashTable。
我的问题是,如何将结构体实例插入 GHashTable 中?有很多关于如何插入字符串或整数的示例(分别使用 g_str_hash 和 g_int_hash ),但我猜测我想使用 g_direct_hash ,但我似乎找不到任何示例。
理想情况下,我的代码如下所示:
GHashtable table;
table = g_hash_table_new(g_direct_hash, g_direct_equal);
struct mystruct;
mystruct.a = 1;
mystruct.b = "hello";
mystruct.c = 5;
mystruct.d = "test";
g_hash_table_insert(table,mystruct.a,mystruct);
显然,这是不正确的,因为它无法编译。任何人都可以提供一个可以实现我想要的功能的示例吗? 谢谢, 里克
I'm trying to build a GHashTable of instances of a struct containing ints, a time_t and a few char*'s.
My question is, how do you insert an instance of a struct into a GHashTable? there are plenty of examples of how to insert a string or an int (using g_str_hash and g_int_hash respectively), but I'm guessing thatI want to use the g_direct_hash, and I can't seem to find any examples of that.
Ideally, my code would look like this:
GHashtable table;
table = g_hash_table_new(g_direct_hash, g_direct_equal);
struct mystruct;
mystruct.a = 1;
mystruct.b = "hello";
mystruct.c = 5;
mystruct.d = "test";
g_hash_table_insert(table,mystruct.a,mystruct);
Clearly, this is incorrect as it does not compile. Can anyone provide an example that does do what I want?
Thanks,
Rik
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能插入自动变量;您必须为要以动态方式存储的数据分配内存,即使用 g_malloc() 或等效方法。
然后,您需要找出一种从数据计算哈希值的方法,以帮助表提高效率。在这里使用 g_direct_hash() 不太好;它将使用指向您的数据的指针作为哈希值。
似乎您想使用结构的成员
a
作为键;这个字段是什么类型?如果是整数,则可以使用g_int_hash()
。我认为这更符合实际代码的样子:
请注意,这假设
b
和d
成员只是字符指针,因为没有存储空间为字符串动态分配。You can't insert an automatic variable; you have to allocate memory for the data to store in a dynamic way, i.e. using
g_malloc()
or equivalent.Then you need to figure out a way to compute a hash value from your data, to help the table be efficient. Using
g_direct_hash()
is not very good here; it will use the pointer to your data as the hash value.It seems as if you want to use the member
a
of your structure as the key; what type is this field? If it's integer, you can useg_int_hash()
.I think this is more along the lines of what your actual code should look like:
Note that this assumes that the
b
andd
members are simply character pointers, since no storage is dynamically allocated for the strings.您必须在堆上分配结构,以便可以在哈希表中存储指针:
您还需要使用 g_hash_table_new_full() ,以便在表被销毁时可以正确释放指针。
You have to allocate the structures on the heap so you can store a pointer in the hash table:
You'll also need to use g_hash_table_new_full() so you can properly free the pointers when the table is destroyed.
谢谢。上面的例子有帮助。阅读这些内容并浏览网上的代码示例后,我可以让它工作。以下是我编写的示例工作代码:
Thanks. The above examples helped. After reading these and going through code samples on the net, I could make it work. Following is a sample working code I wrote: