admin管理员组

文章数量:1123153

I'm writing some C code using GLib and using GHashTable to store some data. However, sometimes I need to do a "reverse lookup" where I need to find the first key that matches a given value. I tried looking through the documentation for GHashTable, but I couldn't find anything like this. Initially, I was hopeful that g_hash_table_find () could do this, but it only returns the value of the key/value pair, so it can't do what I'm asking for.

How can I get the first key that matches a given value in a GHashTable? The definition of "first" doesn't really matter as all values should be unique in my case.

I'm writing some C code using GLib and using GHashTable to store some data. However, sometimes I need to do a "reverse lookup" where I need to find the first key that matches a given value. I tried looking through the documentation for GHashTable, but I couldn't find anything like this. Initially, I was hopeful that g_hash_table_find () could do this, but it only returns the value of the key/value pair, so it can't do what I'm asking for.

How can I get the first key that matches a given value in a GHashTable? The definition of "first" doesn't really matter as all values should be unique in my case.

Share Improve this question asked 7 hours ago NewbyteNewbyte 3,1706 gold badges26 silver badges51 bronze badges 2
  • 1 A loop using a GHashTableIter iterator that you break out of upon finding a matching value. – Shawn Commented 6 hours ago
  • 1 If you need to do this frequently, it might be best to have a second hash table that maps the values back to their keys. – Barmar Commented 6 hours ago
Add a comment  | 

1 Answer 1

Reset to default 0

How can I get the first key that matches a given value in a GHashTable in C?

Hash tables are inherently unordered, so "first key" doesn't make much sense in that context. What you can do is to get the list of keys as an array, sort the array, and then iterate over it checking the corresponding value until you find the one that you're looking for.

本文标签: hashtableHow can I get the first key that matches a given value in a GHashTable in CStack Overflow