So I have a Gtree
which every node is a struct:
typedef struct user {
int id;
char username[256];
int post_count;
char short_bio[16384];
int reputation;
}*USER;
And a GTree:
GTree* users;
What I want to do now is, once I have an ID
I want to search on my Gtree* users
to see if there is an User with the same ID
as that I pass, if there is I want to increment the post_count
variable and stop searching.
Example:
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);
According to the documentation it looks like g_tree_lookup
is a function which you need. It would find a value according to the passed 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).
The code would be similar to:
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
}
}
Let me know if this works for you.