Iterators and hash tables


Whoever used g_hash_table_foreach() knows how painful is to use since C doesn’t have closures, so you have to create a struct to pass local variables to the callback.

Jean-Yves Lefort wrote a patch for bug #500507 (now marked as accept-commit_now) that finally adds iterators to hash tables. Using glib 2.16 you will be able to do this:

GHashTableIter it;
gpointer key;
gpointer value;

g_hash_table_iter_init (table, &it);
while (g_hash_table_iter_next (&it, &key, &value))
  {
    /* do something with key and value */
  }

Thank you Jean-Yves!

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts

Reader Comments

mmh, and why not using the get_keys() and get_values() method I added in GLib 2.14?

keys = g_hash_table_get_keys (table);
for (l = keys; l != NULL; l = l->next)
{
gpointer key = l->data;
gpointer value = g_hash_table_lookup (table, key);

/* do something with key and value */
}
g_list_free (keys);

this new API seems like a bit of syntactic sugar for high level languages refugees, but other than that I don’t really see the point.

Emmanuele Bassi: The iterator safes you the g_list_free and the table lookup, which both do not come for free.

I agree that it’s just a bit of syntactic sugar but a handy bit of syntactic sugar.

get_keys() and get_values() are useful but in this case they are not as handy as iter_init()/_next() and you have to free the list and to do a lookup.

“I agree that it’s just a bit of syntactic sugar but a handy bit of syntactic sugar.”

Agreed. :)