如何在 Gtree (glib) 上搜索元素?
How to search for an element on a Gtree (glib)?
所以我有一个 Gtree
每个节点都是一个结构:
typedef struct user {
int id;
char username[256];
int post_count;
char short_bio[16384];
int reputation;
}*USER;
还有一个 GTree:
GTree* users;
我现在想做的是,一旦我有了一个 ID
,我想在我的 Gtree* users
上搜索,看看是否有一个与那个 ID
相同的用户我通过了,如果有我想增加 post_count
变量并停止搜索。
示例:
I pass to the function id=3 and it searches on the GTree for
a User with id=3 and increments 1 on post_count, using GLIB;
void increment (GTree* a,int id);
根据文档,g_tree_lookup
似乎是您需要的功能。它会根据传递的 gconstpointer key
:
找到一个值
g_tree_lookup ()
gpointer
g_tree_lookup (GTree *tree,
gconstpointer key);
Gets the value corresponding to the given key. Since a GTree is
automatically balanced as key/value pairs are added, key lookup is
O(log n) (where n is the number of key/value pairs in the tree).
代码类似于:
void increment (GTree* a, int id)
{
gpointer ptr = g_tree_lookup (a, &id); // search the tree and find the value
struct user *u = (struct user *) ptr; // cast the `gpointer ` to your pointer to your value
if(u){
u->post_count++; // increment the post_count
}
}
让我知道这是否适合你。
所以我有一个 Gtree
每个节点都是一个结构:
typedef struct user {
int id;
char username[256];
int post_count;
char short_bio[16384];
int reputation;
}*USER;
还有一个 GTree:
GTree* users;
我现在想做的是,一旦我有了一个 ID
,我想在我的 Gtree* users
上搜索,看看是否有一个与那个 ID
相同的用户我通过了,如果有我想增加 post_count
变量并停止搜索。
示例:
I pass to the function id=3 and it searches on the GTree for
a User with id=3 and increments 1 on post_count, using GLIB;
void increment (GTree* a,int id);
根据文档,g_tree_lookup
似乎是您需要的功能。它会根据传递的 gconstpointer key
:
g_tree_lookup () gpointer g_tree_lookup (GTree *tree, gconstpointer key);
Gets the value corresponding to the given key. Since a GTree is automatically balanced as key/value pairs are added, key lookup is O(log n) (where n is the number of key/value pairs in the tree).
代码类似于:
void increment (GTree* a, int id)
{
gpointer ptr = g_tree_lookup (a, &id); // search the tree and find the value
struct user *u = (struct user *) ptr; // cast the `gpointer ` to your pointer to your value
if(u){
u->post_count++; // increment the post_count
}
}
让我知道这是否适合你。