Reputation: 2621
I wish to loop through every key value pair within my hashtable. Therefore I used the g_hash_table_foreach() function (Prototype shown below). For each key value pair, it calls a void func method.
void g_hash_table_foreach(GHashTable *hash_table,GHFunc func,
gpointer user_data);
However, I require that for every call to the function, the method returns a value back.
For example consider the following code:
void calculate(gpointer key, gpointer value, gpointer userdata)
{
return calculateNumbers(key, value);
}
int total = 0;
g_hash_table_foreach(mymap, calculate, NULL);
I require that the variable total stores the total of each returned value received by the calculate() function. I am finding it difficult to do this with the g_hash_table_foreach method.
I would rather have a while loop, declare the total variable outside and increase its value with every iteration over each pair. However, I dont think glib allows to me conider a key-value pair one at a time. (Unlike the GList with has the next attribute) Any ideas how I can do this please?
Upvotes: 4
Views: 4912
Reputation: 399863
That's why the API gives you a "user pointer". Pass whatever data you need there, for instance the address of the total
variable:
static void calculate(gpointer key, gpointer value, gpointer userdata)
{
int *total = userdata;
*total += calculateNumbers(key, value);
}
g_hash_table_foreach(mymap, calculate, &total);
The glib and GTK+ API:s are very good at providing user pointers, which has left me "spoiled"; whenever a see a C API involving callbacks that doesn't (forcing the programmer to use global state) I cringe. And complain. And, if possible, fix it.
UPDATE: Also, for completeness' sake, you actually can do this without the callback, using the GHashTable's "iteration" API.
See the g_hash_table_iter_init()
and g_hash_table_iter_next()
functions. These require at least glib version 2.16.
Upvotes: 7