1

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.

2
  • 3
    A loop using a GHashTableIter iterator that you break out of upon finding a matching value. Commented Jan 10 at 16:57
  • 2
    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. Commented Jan 10 at 17:31

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I did try to clarify that it doesn't matter what "first" really is, I just wrote "first" to distinguish from getting all keys that match a certain value.
@Newbyte OK, so skip the sorting. Just iterate over the keys until you find one with the value you're looking for. If you need better performance than that, you'll need a different data structure.
I ended up writing my own answer that includes some sample code, but thanks for this regardless!
2

I ended up implementing this using GHashTableIter:

gpointer key = NULL, value = NULL;
gchar *matching_key = NULL;
GHashTableIter iter;

g_hash_table_iter_init (&iter, hash_table);
while (g_hash_table_iter_next (&iter, &key, &value)) {
  if (g_str_equal (value, value_to_match)) {
    matching_key = key;
    break;
  }
}

where hash_table is the GHashTable to search through, and value_to_match is the value to find. In this case, the value is a gchar *, so you'd need to change some types and use a different equality function if you want to compare some other kind of data. Additionally, you'll want to check if matching_key is NULL to see if you actually found a match.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.