在数据结构当中,除了链表和树的结构之外,一个重要的角色就是动态数组。它与链表不一样的地方就是内存的分配方式。创建一个链表的时候,在内存方面,是不连续分配的,而动态数组就不一样,它就要求连续分配。而两者的大概功能可以说大同小异吧。它的出现可以就是为了节省内存的使用,进行实时的修改内存的使用,避免冗余。但是如果过于频繁的使用,我个人觉得并不是一件什么好的事。
接触过JAVA的人,对vector这个结构的相关接口应该算是比较了解的,它就是动态数组。以前自己在大学的时候用JSP写过一个简单的聊天室,对于进入聊天室的用户人数进行实时的监控就采用了vector这个结构。
1、定义接口:
- #ifndef _VECTOR_H
- # define _VECTOR_H
- typedef void* value_type;
- typedef struct _Vector Vector;
- typedef void (*VectorDestroyFunc)(value_type data, void* ctx);
- typedef void (*VectorForeachFunc)(value_type data, void* ctx);
- typedef enum _Ret
- {
- RET_FALSE,
- RET_TRUE
- } Ret;
- Vector* vector_create(VectorDestroyFunc destroy_func);
- value_type vector_index_get(Vector* thiz, size_t index);
- Ret vector_append(Vector* thiz, value_type data);
- Ret vector_index_insert(Vector* thiz, value_type data, size_t index);
- Ret vector_index_delete(Vector* thiz, size_t index);
- Ret vector_destroy(Vector* thiz);
- void vector_foreach(Vector* thiz, VectorvectorForeachFunc foreach_func, void* ctx);
- #endif
2、接口的具体实现:
- define ADD_SIZE 100
- struct _Vector
- {
- value_type* data;
- size_t used_size;
- size_t total_size;
- VectorDestroyFunc destroy_func;
- };
- Vector* vector_create(VectorDestroyFunc destroy_func)
- {
- Vector* thiz = (Vector*)malloc(sizeof(Vector));
- thiz->data = NULL;
- thiz->used_size = 0;
- thiz->total_size = 0;
- thiz->destroy_func = destroy_func;
- return thiz;
- }
- value_type vector_get_index(Vector* thiz, size_t index)
- {
- assert(thiz != NULL && index < thiz->total_size);;
- return thiz->data[index];
- }
- static Ret vector_set_memory(Vector* thiz)
- {
- thiz->total_size = thiz->total_size + ADD_SIZE;
- thiz->data = (value_type*)alloc(thiz->data, thiz->total_size * sizeof(value_type));
- return RET_TRUE;
- }
- Ret vector_append(Vector* thiz, value_type data)
- {
- assert(thiz != NULL);
- if(thiz->used_size + 1 > thiz->total_size)
- {
- if(vector_set_memory(thiz) != RET_TRUE)
- return RET_FALSE;
- }
- thiz->data[used_size] = data;
- thiz->total_size ++;
- thiz->used_size ++;
- return RET_TRUE;
- }
- Ret vector_index_insert(Vector* thiz, value_type data, size_t index);
- Ret vector_index_delete(Vector* thiz, size_t index);
- Ret vector_destroy(Vector* thiz);
3、实现一下遍历函数:
- void vector_foreach(Vector* thiz, VectorForeachFunc foreach_func, void* ctx)
- {
- assert(thiz != NULL);
- size_t index = 0;
- while(thiz->used_size == index)
- {
- foreach_func(thiz->data[index], ctx);
- index++;
- }
- return ;
- }