Windows XP Tablet Ed.Visual C++ 9.0Visual C++ 7.1Visual C++ 8.0Windows VistaVisual C++ 7.0C++/CLIWindows 2003Windows 2000Visual C++ 6.0高级Windows XPMFC初级C中级开发WindowsC++
高效动态数组和一个简单的演示
帮助你管理动态数组

引言
如果您正在寻找一个高效的动态数组,我相信这段代码会很有用。我称它为 CSArray。它是 C++ 的一个模板类。它包装了数组运算符,包括 MFC 的 CArray 的几乎所有接口和一些新功能。此外,它还提供了良好的排序能力。如果您需要将数据保持排序,您不再需要编写排序函数,而是提供一个简单的数据比较回调函数。最后但并非最不重要的是,您可以通过指定增长大小属性来告诉 CSArray 如何使用内存。您可以调用 Add、RemoveAt 等。在您享受这些好处的同时,您无需担心它会浪费内存,因为 CSArray 可以自动整理数据数组。
下图展示了我如何在 CSArray 中管理数据。乍一看,有人可能会怀疑它是一个普通的列表。事实上,它结合了列表和数组,因此,它具有像数组一样的高效率和像列表一样的高灵活性。如果我们设置增长为 1,它就是一个纯列表,如果我们设置增长足够大,它就是一个纯数组。
使用代码
我是一个中国人。在演示中,我使用我的一个中文字典作为源数据,因为我没有时间为它准备这么多测试数据。它的文件名是 userdef.txt。可以使用这些功能按钮来了解如何操作 CSArray。我使用虚拟列表控件来显示数据。
CSArray 支持 MFC 的 CArray 的几乎所有接口。如果您在代码中使用 CArray,您会发现将 CArray 转换为 CSArray 非常容易,除了 CSArray 仅接受一个模板参数。
接下来,我将介绍一些新功能。
void SetGrowBy(WORD nGrowBy) //function: tell how much rooms should be allocated when there is no empty room for new element. //remark: the function should be call at the begin of use CSArray or after you have called RemoveAll. //In one word, before call it, make sure that CSArray is empty. int SortFind(T *pData,FUNCMP funCmp=NULL,LPARAM lParam=0,int nBegin=0,UINT sfType=SFT_ANY) //function: find element in a sorted array. //param //T *pData[in]:specify what element you try to find. //FUNCMP funCmp[in]:callback data compare function. If it is NULL, CSArray use memcmp to replace. //LPARFAM lParam[in]:a user defined 32bits data, used in funCmp. //int nBegin[in]:tell CSArray to start search from here. //UINT sfType[in]:tell CSArray how to do while there are several elements which satisfy the conditions you offered. //SFT_ANY will return any equal element, SFT_HEAR will return the first matched element //and SFT_TAIL will return the last matched element. //return: a found element index. -1 is no element found. int SortInsert(T newElement,BOOL bRepeat=TRUE,FUNCMP funCmp=NULL,LPARAM lParam=0,UINT sfType=SFT_ANY) //function:insert an element to array and keep array sorted. //T newElement[in]: target element to be inserted. //BOOL bRepeat[in]: indicate whether compared equal elment should be inserted. //If false and if find a equal element, function return -1. //FUNCMP funCmp,LPARAM lParam,UINT sfType[in]:same as SortFind. //return: new inserted element index. -1 is not inserted. //remark:sfType tell CSArray how to insert a compared equal element. BOOL Attach(T *pData,int nLen) //function: attach an external data block to CSArray. T *Detach(int *pnLen) //function: remove external data from CSArray. //remark: sometime we have a sorted data, and we need to index an element quickly, //we can simply hand data to CSArray. If doing so, for most case, //try not to call interfaces such as "add","removeat",etc.
警告!!!
CSArray 应该用于结构体数据,而不是类数据,因为我使用 memcpy、memmove 等来整理数据。
历史
2008-9-25:提交