chashtableglib

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


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.


Solution

  • 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.