读书人

在C语言中大略实现VC++中的LISTARRAY功

发布时间: 2012-06-20 20:37:21 作者: rapoo

在C语言中大概实现VC++中的LISTARRAY功能方法(二)
#ifndef __LISTARRAY_H__#define __LISTARRAY_H__#include "rtthread.h"#include "finsh.h"#define LISTDEFAULTSIZE 20#define LISTCHANGESIZE 10//LIST数组typedef struct _List List;struct _List{ void **pListPointArray; //LIST数组指针 int Total; //元素个数 int ChangeSize; //每次改变容量的时候容量的大小 int Size; //当前容量 void (*Add)(List *pList, void *pListPoint); //添加 void (*Remove)(List *pList, void *pListPoint); //移除 void (*Delete)(void *pList); //析构};//List类的析构函数static void ListDelete(void *pList){ rt_free(((List *)pList)->pListPointArray); rt_free(pList); //再释放整个List类}//元素增加函数static void ListAdd(List *pList, void *pListPoint){ void **tListPointArray; if(pList->Size == pList->Total) //如果空间已满 { pList->Size = pList->Size + pList->ChangeSize; //改变空间的尺寸 tListPointArray = rt_malloc(sizeof(int *) * pList->Size); //重新申请内存 memcpy(tListPointArray, pList->pListPointArray, sizeof(int *) * pList->Total); //将原内存的数据拷到新内存 rt_free(pList->pListPointArray); //释放原空间 pList->pListPointArray = tListPointArray; //将新空间指针代替原空间指针 } pList->pListPointArray[pList->Total] = pListPoint; //将添加的元素放到最后一个存储单元中 pList->Total++; //个数加1}//元素移除函数static void ListRemove(List *pList, void *pListPoint){ int pListIndex, tListIndex; void **tListPointArray; if(pList->Total == 0) return; //总数为0时退出 for(pListIndex = 0, tListIndex= 0; pListIndex < pList->Total; pListIndex++) //查找移除点 { if(pList->pListPointArray[pListIndex] != pListPoint) //当前点不是移除点 { pList->pListPointArray[tListIndex] = pList->pListPointArray[pListIndex]; //拷贝 tListIndex++; //拷贝序号加1 } } pList->Total = tListIndex; if(pList->Total <= (pList->Size - pList->ChangeSize)) { pList->Size = pList->Size - pList->ChangeSize; //改变内存尺寸 tListPointArray = rt_malloc(sizeof(int *) * pList->Size); //申请新内存 memcpy(tListPointArray, pList->pListPointArray, sizeof(int *) * pList->Total);//拷贝数据 rt_free(pList->pListPointArray); //释放原空间 pList->pListPointArray = tListPointArray; //将新空间指针代替原空间指针 }}//List构造函数static List *ListCreate(void){ List *pList = (List *)rt_malloc(sizeof(List)); pList->Total = 0; pList->Size = LISTDEFAULTSIZE; pList->ChangeSize = LISTCHANGESIZE; pList->pListPointArray = rt_malloc(LISTDEFAULTSIZE); pList->Add = ListAdd; pList->Remove = ListRemove; pList->Delete = ListDelete; return pList;}#endif


此方法是由方法1发展而来,在方法1中添加了两个参数,一个是SIZE参数,一个是CHANGESIZE参数,SIZE参数是初始化时的数组容量,CHANGESIZE是在数据刚好达到SIZE时将数组容量改变的数组添加或减少的容量。比如初始大小为SIZE,然后当数组增加到SIZE的时候要存储第SIZE + 1个数据的时候就重新申请一块比SIZE大CHANGESIZE的内存,然后再将数据转移进去,将原内存释放,将新内存的指针保存。减少是一个道理的,当减到SIZE的时候,将原尺寸减个CHANGESIZE,然后申请内存,转移数据,释放老内存,保存新指针。

此方法的好处是不用每次都申请、释放内存、转移数据,操作LIST比较频繁的时候,用此方法比用第1种方法在速度上有优势!

读书人网 >C语言

热点推荐