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!

4 thoughts on “Iterators and hash tables

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


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


Comments are closed.