c - 为什么不增加?

标签 c search data-structures glib

所以我试图做一个函数,它接受一个 GTree* a(Tree 的每个节点都是一个 struct User)和一个 id,它会搜索那个 user 并增加一个变量! (学校项目)

在此处的一些帮助下,我设法做到了,但我没有意识到它没有递增。

结构是:

typedef struct user {
    int id;
    char username[256]; 
    int post_count; 
    char short_bio[16384]; 
    int reputation;
}*USER;

typedef struct TCD_community{
    GTree* res;    
    GTree* quest; 
    GTree* users; /
}TCD_community;

typedef struct TCD_community * TAD_community;

TAD_community tq;

函数是(在 stackoverflow 用户的帮助下):

void incrementaPost(GTree* a,int id){

    gpointer ptr = g_tree_lookup ( a , &id);   

    struct user *u = (struct user *) ptr; 

    if(u){
        u->post_count++;  
    }
}

我在 main 上这样调用它:

incrementaPost( tq -> users, 703994);

输出:

Id 703994 
Name N.Sinha 
post_count 0 
reputation 51

预期:

Id 703994 
Name N.Sinha 
post_count 1 
reputation 51

最佳答案

请注意,GTree* 必须先正确构建,然后才能进行搜索。

首先用专用搜索函数构造树:

GTree   *tree;
tree = g_tree_new(MySearchFunction);

在哪里

g_tree_new ()

GTree * g_tree_new (GCompareFunc key_compare_func);

Creates a new GTree.

Parameters:

key_compare_func

the function used to order the nodes in the GTree. It should return values similar to the standard strcmp() function -0 if the two arguments are equal, a negative value if the first argument comes before the second, or a positive value if the first argument comes after the second.

然后你的对象必须使用 g_tree_insert () 插入

g_tree_insert ()

void g_tree_insert (GTree *tree, gpointer key, gpointer value);

Inserts a key/value pair into a GTree.

If the given key already exists in the GTree its corresponding value is set to the new value. If you supplied a value_destroy_func when creating the GTree, the old value is freed using that function. If you supplied a key_destroy_func when creating the GTree, the passed key is freed using that function.

Parameters

tree

  • a GTree

key

  • the key to insert

value

  • the value corresponding to the key

只有这样,您才能使用 g_tree_lookup 进行搜索。

Check this simple example - 如何构造 GTree*、插入元素、通过 g_tree_lookup 进行搜索并通过 g_tree_traverse 遍历树。

关于c - 为什么不增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49588612/

相关文章:

linux - 用于在文本文件中查找模式并返回整行的 bash 脚本

c++ - 在我的实现中使用堆栈是否正确?

c# - ConcurrentDictionary.TryUpdate 方法中的 ComparisonValue 参数的原因是什么?

c - 确定质数或合数

c++ - 未定义、未指定和实现定义的行为

c - 递归树遍历,为树的每个叶子返回一个变量

c++ - 如何查找无序数(线性搜索)

api - 通过 API 搜索 Apple Appstore 名称?

list - Haskell 中最先进的廉价列表操作?

c - 在 C : square brackets vs. 指针中传递数组