2014年01月24日 星期五 09:20
C语言标准库缺失了一种常用且重要的数据结构,这就是哈希表。没有动态的vector,我们可以使用数组来凑合用,但没有哈希表,确实很难办,期待“C1x”标准能够带来更加丰富标准库。APR的Hash Table模块提供了很好用的哈希表的实现,编程示例如下:
#include <stdio.h> #include <apr.h> #include <apr_pools.h> #include <apr_errno.h> #include <apr_strings.h> #include <apr_time.h> #include <apr_hash.h> void apr_err(const char *s, apr_status_t rv) { char buf[120]; fprintf(stderr, "%s: %s (%d)\n", s, apr_strerror(rv, buf, sizeof buf), rv); } int main(int argc,char **argv) { apr_initialize(); apr_pool_t *pool; apr_pool_create(&pool,NULL); apr_status_t st; apr_hash_t *ht; ht=apr_hash_make(pool); char *key; char *value; key="laomeng"; value="laomeng188@163.com"; apr_hash_set(ht,key,strlen(key),value); key="laozhang"; value="laozhang250@163.com"; apr_hash_set(ht,key,strlen(key),value); char *getvalue=apr_hash_get(ht,key,strlen(key)); printf("getvalue : %s\n",getvalue); printf("total items: %u\n",apr_hash_count(ht)); apr_hash_index_t *idx; char *k=NULL; char *v=NULL; for(idx=apr_hash_first(pool,ht);idx != NULL;idx=apr_hash_next(idx)) { apr_hash_this(idx,(const void **)&k,(apr_ssize_t *)NULL,(void **)&v); printf("%s => %s\n",k,v); } apr_hash_set(ht,key,strlen(key),NULL); printf("total items: %u\n",apr_hash_count(ht)); apr_hash_clear(ht); printf("total items: %u\n",apr_hash_count(ht)); getvalue=apr_hash_get(ht,key,strlen(key)); printf("getvalue : %s\n",getvalue); apr_pool_destroy(pool); apr_terminate(); return 0; }
参考资料:
http://apr.apache.org/docs/apr/1.3/group__apr__hash.html
Zeuux © 2024
京ICP备05028076号