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

来源:互联网 发布:阿里巴巴直接传淘宝 编辑:程序博客网 时间:2024/06/13 09:06

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); * * typedefstruct 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;}