[C++] C语言 uthash哈希使用范例 →→→→→进入此内容的聊天室

来自 , 2020-11-21, 写在 C++, 查看 111 次.
URL http://www.code666.cn/view/e55bc025
  1. #include "uthash.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. /*这个uthash必须构造一个结构体*/
  5. struct packet
  6. {
  7.         int key;            /*这个是用来做hash的key值*/
  8.         char msg[10];
  9.         UT_hash_handle hh; /*这个结构是uthash的结构体,里面包含next,prev,hash值等信息*/
  10. };
  11.  
  12. int main()
  13. {
  14.         struct packet *pkt, *tmp;
  15.         int i;
  16.         struct packet *hash_packet = NULL; /*必须初始化为NULL*/
  17.  
  18.         /*打印这个hash的节点数*/
  19.         printf ("hash count = %d \n", HASH_COUNT(hash_packet));
  20.  
  21.         /*往hash中添加节点*/
  22.         for (i=0; i<10; i++)
  23.         {
  24.                 pkt = (struct packet *)malloc(sizeof(struct packet));
  25.                 pkt->key = i;
  26.                 sprintf (pkt->msg, "i=%d", i);
  27.  
  28.                 HASH_FIND_INT(hash_packet, &i, tmp);
  29.                 if (tmp != NULL)
  30.                 {
  31.                         printf ("The key(%d) exists in hash. \n", i);
  32.                         continue;
  33.                 }
  34.                 HASH_ADD_INT(hash_packet, key, pkt);
  35.                 printf ("insert item. key=%d,value=%p \n", i, pkt);
  36.         }
  37.         printf ("hash count = %d \n", HASH_COUNT(hash_packet));
  38.  
  39.         /*通过key查找*/
  40.         for (i=0; i<13; i++)
  41.         {
  42.                 HASH_FIND_INT(hash_packet, &i, tmp);
  43.                 if (tmp == NULL)
  44.                 {
  45.                         printf ("find not item. key=%d,value=%p \n", i, tmp);
  46.                         continue;
  47.                 }
  48.                 printf ("find item. key=%d,value=%p \n", i, tmp);
  49.         }
  50.  
  51.         printf ("hash count = %d \n", HASH_COUNT(hash_packet));
  52.  
  53.         /*遍历这个hash表*/
  54.         struct packet* mytemp = NULL;
  55.         for (mytemp = hash_packet; mytemp != NULL; mytemp = (packet*)mytemp->hh.next)
  56.                 printf (" %d => %s \n", mytemp->key, mytemp->msg);
  57.         /*删除节点*/
  58.         for (i=0; i<13; i++)
  59.         {
  60.                 HASH_FIND_INT(hash_packet, &i, tmp);
  61.                 if (tmp == NULL)
  62.                 {
  63.                         printf ("find not item. key=%d,value=%p \n", i, tmp);
  64.                         continue;
  65.                 }
  66.                 /*删除节点不会释放你的空间必须自己释放*/
  67.                 HASH_DEL(hash_packet, tmp);
  68.                 free(tmp);
  69.                 printf ("delete itme. key=%d,value=%p \n", i, tmp);
  70.         }
  71.         printf ("hash count = %d \n", HASH_COUNT(hash_packet));
  72.  
  73.         system("pause");
  74.         return 0;
  75. }
  76. //cpp/8955

回复 "C语言 uthash哈希使用范例"

这儿你可以回复上面这条便签

captcha