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;
else
memcpy(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;
else
return 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;
else
memcpy(, 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;
}