C语言--容器的实现。

来源:互联网 发布:mac装双系统分区 编辑:程序博客网 时间:2024/06/10 05:40

 *引用本文请注明来自 blog.csdn.net/wtz1985       

容器(container)这个词眼,相信大家都不陌生了,特别是JAVA或C#的人,应该是比较熟悉了,它只是一个中间接口,也就是一个纯虚类。它的实现可以通过链表或者数组等结构,它的出现就是为了其他函数体可以自由地选择适合自己的实现结构。比如哈希表、堆栈等结构,既可以用链表实现,也可以用动态数组实现,如果没有一个中间接口的话,想要实现它,那就要分开实现了,这样太浪费时间和空间了。

1、接口定义。

  1. /*----- container.h -------*/
  2. #ifndef _CONTAINER_H 
  3. #define _CONTAINER_H 
  4. struct _Container;
  5. typedef struct _Container Container;
  6. yptedef void (*ForeachFunc)(void*  data, void* ctx);
  7. typedef void* (*ContainerAppendFunc)(Container* thiz, void* data);
  8. typedef void* (*ContainerInsertFunc)(Container* thiz, void* data, size* index);
  9. typedef void* (*ContainerDeleteFunc)(Container* thiz,  size_t index);
  10. typedef void  (*ContainerDestroyFunc)(Container* thiz);
  11. typedef void  (*ContainerForeachFunc)(Container* thiz, ForeachFunc print, void* ctx);
  12. struct _Container
  13. {
  14.   ContainerAppendFunc container_append;
  15.   ContainerInsertFunc container_insert;
  16.   ContainerDeleteFunc container_delete;
  17.   ContainerDestroyFunc container_func;
  18.   ContainrForeachFunc  container_foreach;
  19.   char priv[0];
  20. };
  21. static inline void* container_append(Container* thiz, void* data)
  22. {
  23.   assert(thiz != NULL && thiz->container_append != NULL);
  24.   return thiz->container_append(thiz, data);
  25. }
  26. static inline void* container_insert(Container* thiz, void* data, size_t index)
  27. {
  28.   assert(thiz != NULL && thiz->container_insert != NULL);
  29.   return thiz->container_insert(thiz, data, index);
  30. }
  31. static inline void* container_delete(Container* thiz, size_t index)
  32. {
  33.   assert(thiz != NULL && thiz->container_delete != NULL);
  34.   return thiz->container_delete(thiz, index);
  35. }
  36. static inline void container_destroy(Container* thiz)
  37. {
  38.   assert(thiz != NULL && thiz->container_destroy != NULL);
  39.   return thiz->container_destroy(thiz);
  40. }
  41. static inline void  container_foreach(Container* thiz, ForeachFunc print, void* ctx)
  42. {
  43.   assert(thiz != NULL && thiz->container_foreach != NULL);
  44.   return thiz->container_foreach(thiz, print, ctx);
  45. #endif /_CONTAINER_H/

2、不同的接口实现:

链表:

  1. /*------- container_list.h ---------*/
  2. #include "container.h" 
  3. #include "dlist.h" 
  4. #ifndef _CONTAINER_LIST_H 
  5. #define _CONTAINER_LIST_H 
  6. Container* container_list_create(DList* list); 
  7. #endif  /*_CONTAINER_H*/

动态数组

  1. /*---------  container_vector.h -----------*/
  2. #include "vector.h" 
  3. #include "container.h" 
  4. #ifndef _CONTAINER_VECTOR_H 
  5. #define _CONTAINER_VECTOR_H 
  6. Container* container_vector_create(Vector* thiz); 
  7. #endif /*CONTAINER_VECTOR_H*/

有了这些接口,具体的实现,就不必再写,相信大家都应该知道了,如果有写得不好的地方,请大家再指教指教。

 

~~end~~