C++ SDK沒有直接提供動態數組功能,雖然可以使用MFC的CArray類,或者用指標+new來實現,但前者需要MFC庫,後者使用時不易理解且運行效率低,為此,我把很久前自己寫的一個簡單的動態數組類貼出來,希望給一些朋友啟發。
代碼說明:本類在數群組成員的賦值和記憶體配置上作了最佳化,對大數組的效能有明顯提高。
使用方法:將代碼複製到標頭檔CMyArray.h檔案中,在項目中引用該檔案即可。
一、標頭檔CMyArray.h
#ifndef __TDARRAY_H__#define __TDARRAY_H__#include <windows.h>#include <tchar.h>template <typename T> class CMyArray{private:T *m_pArray; //記憶體指標DWORD m_nItemCount; //成員總數量DWORD m_nBlockCount; //記憶體塊數量DWORD m_nItemsPerBlock; //每個記憶體塊中包含的成員數量DWORD m_dwAllocationGranularity; //記憶體配置粒度(即記憶體塊大小)DWORD ITEM_SIZE;public:CMyArray(){SYSTEM_INFO si;GetSystemInfo(&si);m_dwAllocationGranularity = si.dwAllocationGranularity;m_nItemCount = 0;m_nBlockCount = 0;m_pArray = NULL;ITEM_SIZE = sizeof(T);m_nItemsPerBlock = m_dwAllocationGranularity / ITEM_SIZE;};~CMyArray(){if(m_pArray)GlobalFree(m_pArray);};T* Add(T item){return Add(&item);};T* Add(T *item){if(!m_pArray){m_pArray = (T*)GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT, m_dwAllocationGranularity);if(!m_pArray)throw _T("記憶體溢出");m_nBlockCount = 1;}else{if(m_nItemCount % m_nItemsPerBlock == 0){m_nBlockCount ++;m_pArray = (T*)GlobalReAlloc(m_pArray, m_nBlockCount * m_dwAllocationGranularity, GMEM_MOVEABLE | GMEM_ZEROINIT);if(!m_pArray)throw _T("記憶體溢出");}}T* p = m_pArray+m_nItemCount;if(ITEM_SIZE <= 8)*p = *item;elsememcpy(p, item, ITEM_SIZE);m_nItemCount++;return p;};BOOL Remove(DWORD position){if(position<m_nItemCount-1){memcpy(m_pArray+position, m_pArray+position+1, (m_nItemCount-1-position)*ITEM_SIZE);m_nItemCount--;return TRUE;}return FALSE;};VOID Clear(){if(m_pArray)GlobalFree(m_pArray);m_nItemCount = 0;m_nBlockCount = 0;m_pArray = NULL;};T* GetItem(DWORD position){if(position < m_nItemCount)return m_pArray+position;elsereturn NULL;};T GetItemValue(DWORD position){return *(m_pArray+position);};BOOL SetItem(DWORD position, T item){return SetItem(position, &item);};BOOL SetItem(DWORD position, T *item){if(position < m_nItemCount){T *p = m_pArray + position;if(ITEM_SIZE <= 8)*p = *item;elsememcpy(, item, ITEM_SIZE);return TRUE;}return FALSE;};DWORD GetCount(){return m_nItemCount;};};#endif //__TDARRAY_H__
二、測試代碼:
#include "stdafx.h"#include <stdio.h> #include <dos.h> #include <conio.h> #include "CMyArray.h"int main(void) { long i;//執行個體化數組類CMyArray<long> *pArray = new CMyArray<long>();//添加數群組成員for(i=1; i<100000; i++){pArray->Add(i);}//移出數群組成員pArray->Remove(99991);//獲得數群組成員個數long nCount = pArray->GetCount();//顯示部分數群組成員for(i=99990; i<nCount; i++){printf("第 %d 成員的值:%d。\r\n", i, pArray->GetItemValue(i));}//銷毀數組對象delete pArray;getchar();return 0;}