(5) hashtable <key, data> : hcreate hdestroy hsearch

本文通过一个具体的示例展示了如何使用hcreate(), hsearch(), 和hdestroy()函数创建和操作哈希表。示例中涉及的数据结构关联了城市名称与当地特色食物及其价格,通过这些函数实现了数据的插入和查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The  three functions hcreate(), hsearch(), and hdestroy() allow the user to create a hash table (only one at a time) which associates a key with any data.


#include <stdio.h>
#include <stdlib.h>
#include <search.h>

/*
 *
 * int hcreate(size_t nel);
 * void	 hdestroy(void);
 *
 * typedef	struct entry {
		char	*key;
		void	*data;
   } ENTRY;

 * ENTRY *hsearch(ENTRY item, ACTION action);
 * if not found
 * 	 if (ACTION is specified with ENTER)
 * 	 	insert a copy of item
 * 	 else if(ACTION is specified with FIND)
 * 	 	return NULL.
 */
struct food{
	char *name;
	int price;
};

struct city_food{
	char *key;
	struct food most_famous_food;
};

typedef struct city_food city_food_t;

city_food_t city_food_array[] = {
		{"beijing", {"douzhi", 2}},
		{"xian", {"yangroupaomo", 20}},
		{"tianjin", {"damahua", 5}},
		{"nanjing", {"yaxuefengsi", 8}},
		{"wuhan", {"reganmian", 3}},
		{"lanzhou", {"lamian", 7}},
		{"zhengzhou", {"huimian", 18}}
};

#define SIZE sizeof(city_food_array)/sizeof(city_food_t)

int main(int argc, char **argv){
	 /* starting with small table, and letting it grow does not work */
	 hcreate(5);  //create a hash table with an  estimate  of  the number

	 int i;
	 ENTRY e, *ep;
	 for (i = 0; i < SIZE; i++) {
		 e.key = city_food_array[i].key;
		 e.data = &city_food_array[i].most_famous_food;
		 ep = hsearch(e, ENTER);  //************
		 if(!ep){
			 fprintf(stderr, "failure started with #%d\n", i);
//			 exit(1); //should not use exit, otherwise the latter coding will not run
		 }
	 }

	 for(i = 0; i < SIZE; i++){
		 e.key = city_food_array[i].key;
		 ep = hsearch(e, FIND);//************
		 if(ep){
			 printf("#%d, %s is found.\n", i, ep->key);
			 printf("==={%s, {%s, %d}}\n", ep->key, ((struct food *)ep->data)->name, ((struct food *)ep->data)->price);
		 }else{
			 printf("#%d, %s is not found.\n", i, e.key);
		 }
	 }

	 hdestroy();
	 return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值