实现的ATL(AtlSimpleArray)数组任意插入辅助函数

前言:

   最近在写树中用到了数组,ATL中的 AtlSimpleArray 这个类封装了一个简单数组,简单高效。

正因为简单,没有带插入数据功能, 下面是我实现的一个函数,任意位置插入。 两句内存操用。 这样做有一个不好的地方是,容易产生内存碎片。 所以如果操作非常非常多 就要用List了。


look source

#include "stdafx.h"

#include <atlcoll.h>

class DemoClass

{

public:

DemoClass(int num)

{

m_num = num;

}

~DemoClass()

{

printf("析构%d\n", m_num);

}

int m_num;

};


int _tmain(int argc, _TCHAR* argv[])

{

CSimpleArray<DemoClass*> arrys;

for (int i = 0; i < 400; i ++)

{

arrys.Add(new DemoClass(i));

}

int iIndex = 4;

/////////////////////////////////////

if( ++arrys.m_nSize >= arrys.m_nAllocSize)

{

DemoClass** aT;

int nNewAllocSize = (arrys.m_nAllocSize == 0) ? 1 : (arrys.m_nSize * 2);

if (nNewAllocSize<0||nNewAllocSize>INT_MAX/sizeof(DemoClass*))

{

return FALSE;

}

aT = (DemoClass**)_recalloc(arrys.m_aT, nNewAllocSize, sizeof(DemoClass*));

if(aT == NULL)

return FALSE;

arrys.m_nAllocSize = nNewAllocSize;

arrys.m_aT = aT;


}

if (arrys.m_aT)//not null

{

memmove(&arrys.m_aT[iIndex + 1], &arrys.m_aT[iIndex], (arrys.m_nSize - iIndex - 1) * sizeof(DemoClass*));

// 5在3处插入 移动 345 

//////////////////

//

// 5插入

//  0 1 2 3 ^ 4 5 6 7 8 9 

//

}

//arrys.m_aT[iIndex] = new DemoClass(88888);

DemoClass* bbc = new DemoClass(88888);

arrys.SetAtIndex(iIndex, bbc);

int j = 0;

while(j < arrys.GetSize())

{

printf("%d\n", arrys[j]->m_num);

j++;

}

printf("%d\n", arrys.GetSize());

return 0;

}


posted @ 2011-07-21 14:34  MokLiu  阅读(701)  评论(0编辑  收藏  举报