UTHASH 字符串key值使用

UTHASH User Guide

A string key

  1. Include:
    #include "uthash.h"
  2. Data sturcture:
typedef struct {
    char ID[10];                    /* key */
    char name[10];
    int age;
    UT_hash_handle hh;         /* makes this structure hashable */
}HashTable;
  1. Declaration:
    HashTable *g_table = NULL Remember to initialize to NULL and preferably be global variable.
    Otherwise, better to pass a pointer to the hash pointer (the hash macros modify it)
/* bad, but works with Hash as global variable */
void add_user(struct my_struct *hash, int user_id, char *name) {
  ...
  HASH_ADD_INT(hash, id, s);
}
/* good */
void add_user(struct my_struct **pHash, int user_id, char *name) { ...
  ...
  HASH_ADD_INT(*pHash, id, s);
}
  1. Add
    The second parameter is the name of the key field
HashTable *s;
s = (HashTable  *)malloc(sizeof *s);
strcpy(s->ID, keyID);
strcpy(s->name, name);
HASH_ADD_STR(g_table, ID, s);
  1. Find
HashTable *s;
HASH_FIND_STR(g_table, "123456", s);
if (s) 
	printf("123456's name is %d\n", s->name);
  1. Delete and deletion-safe iteration
HashTable *s,*tmp;
HASH_ITER(hh, g_table, s, tmp) {
      HASH_DEL(users, s);
      free(s);
	  }
  1. Sort:
    Items are iterated in insertion order by default. It can be sorted by calling HASH_SORT(hashTable, SortFunc)
int by_name(const struct my_struct *a, const struct my_struct *b) {
    return strcmp(a->name, b->name);
}

void sort_by_name() {
    HASH_SORT(users, by_name);
}
  1. Count
unsigned int num_users;
num_users = HASH_COUNT(g_table);

A pointer key

#include <stdio.h>
#include <stdlib.h>
#include "uthash.h"

typedef struct {
  void *key;
  int i;
  UT_hash_handle hh;
} el_t;

el_t *hash = NULL;
char *someaddr = NULL;

int main() {
  el_t *d;
  el_t *e = (el_t *)malloc(sizeof *e);
  if (!e) return -1;
  e->key = (void*)someaddr;
  e->i = 1;
  HASH_ADD_PTR(hash, key, e);
  HASH_FIND_PTR(hash, &someaddr, d);
  if (d) printf("found\n");

  /* release memory */
  HASH_DEL(hash, e);
  free(e);
  return 0;
}

Note:

  • Need to guarateen uniqueness of key
  • Convenience/General macros: make UT_hash_handle named hh to use convenience macros, support integer, pointer or string keys, otherwise name UT_hash_handle except hh!
  • Key must not be modified while in-use
  • 14
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值