我希望循环遍历哈希表中的每个键值对 . 因此我使用了g_hash_table_foreach()函数(Prototype如下所示) . 对于每个键值对,它调用 void func方法 .
void g_hash_table_foreach(GHashTable *hash_table,GHFunc func,
gpointer user_data);
但是,我要求每次调用该函数时,方法 returns 返回一个值 .
例如,请考虑以下代码:
void calculate(gpointer key, gpointer value, gpointer userdata)
{
return calculateNumbers(key, value);
}
int total = 0;
g_hash_table_foreach(mymap, calculate, NULL);
我要求变量total存储calculate()函数接收的每个返回值的总和 . 我发现使用g_hash_table_foreach方法很难做到这一点 .
我宁愿有一个while循环,在外部声明总变量,并在每对迭代时增加其值 . 但是,我不认为glib允许我一次控制一个键值对 . (与具有下一个属性的GList不同)任何想法我怎么能这样做呢?
1 回答
这就是API为您提供"user pointer"的原因 . 传递您需要的任何数据,例如
total
变量的地址:glib和GTK API:s非常擅长提供用户指针,这让我“被宠坏了”;每当看到一个涉及不回调的C API(迫使程序员使用全局状态)时,我都会感到畏缩 . 抱怨并且,如果可能的话,修复它 .
UPDATE :另外,为了完整性' sake, you actually can do this without the callback, using the GHashTable' s "iteration" API .
请参阅g_hash_table_iter_init()和g_hash_table_iter_next()函数 . 这些至少需要glib版本2.16 .