从 GLib GTree 中提取所有值

Extracting all values from a GLib GTree

我构建了一个 GLib GTree,其中包含 key/value 对,其中键是一个字符(例如 'a'),值是该字符出现的频率一个字符串。例如,如果字符串是 'aaa',那么树中的唯一元素将是:'a' => 3.

我想做的是遍历树并计算具有给定频率的字符数,即 key/value 对匹配的值。

伪代码类似于:

frequency_count = 0
while (current_element = get_next_element)
  if (current_element->value == desired_frequency)
    frequency_count = frequency_count + 1

有没有办法用 GTree 做到这一点?我能找到的唯一函数是 g_tree_foreach(),但这需要我传递一个 returns TRUE 的回调函数来停止遍历树,我不想停止遍历,直到我已经访问了每个元素。我是否应该使用回调函数的 gpointer user_data 参数来传递频率计数和所需的频率值?

Am I supposed to use the gpointer user_data parameter of the callback function to pass in the frequency count and desired frequency values?

是的。

示例:

typedef struct
{
  guint desired_frequency;
  guint n_matches;
} MatchData;

static gboolean
n_nodes_matching_frequency_cb (gpointer key,
                               gpointer value,
                               gpointer user_data)
{
  MyTreeElement *element = value;
  MatchData *data = user_data;

  if (element->value == data->desired_frequency)
    data->n_matches++;

  return FALSE;
}

guint
n_nodes_matching_frequency (GTree *tree,
                            guint  desired_frequency)
{
  MatchData data = { desired_frequency, 0 };
  g_tree_foreach (tree, n_nodes_matching_frequency_cb, &data);
  return data.n_matches; 
}