哈希表,C语言

struct my_struct{
    int id;  /* key */
    int val;
    UT_hash_handle hh; /* makes this structure hashable */
};

struct my_struct *users = NULL;

直接添加元素

/* Add item */
void add_user(int user_id, int user_val){
    struct my_struct *s;
    s = (struct my_struct *)malloc(sizeof(struct my_struct));
    s->id = user_id;
    s->val = user_val;
    HASH_ADD_INT(users, id, s);
}

先检查哈希表中是否存在该元素

/* Add an item to a hash */
void add_user(int user_id, int user_val){
    struct my_struct *s;
    HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */
    if(s==NULL){
        s = (struct my_struct *)malloc(sizeof(struct my_struct));
        s->id = user_id;
        HASH_ADD_INT(users, id, s);
    }
    s->val = user_val;
}

/* Find a structure using its key */
struct my_struct *find_user(int user_id){
    struct my_struct *s;
    HASH_FIND_INT(users, &user_id, s); /* s: output pointer */
    return s;
}

/* Delete an item from a hash */
void delete_user(struct my_struct *user){
    HASH_DEL(users, user); /*user: pointer to delete */
    free(user);       /* optional */
}

/* Delete all items from a hash */
void delete_all(){
    struct my_struct *current_user, *tmp;
    HASH_ITER(hh, users, current_user, tmp){
        HASH_DEL(users, current_user); /* delete; users advances to next */
        free(current_user); /* optional - if you want to free */
    }
}

/* All-at-once deletion */
HASH_CLEAR(hh, users);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值