一个动态数组的实现.

Posted on 2007-03-30 11:59  啊夏  阅读(419)  评论(0编辑  收藏  举报
     在项目过程中,有时候需要一些能索引的,可以动态插入的,无长度限制的数据结构.
使用STL是可以很方便,但是在mobile上,不想引入STL. 就自己简单地实现了一个这样的结构.
采用模版类的方式来设计.用起来基本还可以.

   模版的实现
template<class T>
class CDynArray
{
public:

    CDynArray()
    
{
        mPT 
= NULL;
        nCount 
= 0;
  &nb%2
     在项目过程中,有时候需要一些能索引的,可以动态插入的,无长度限制的数据结构.
使用STL是可以很方便,但是在mobile上,不想引入STL. 就自己简单地实现了一个这样的结构.
采用模版类的方式来设计.用起来基本还可以.

   模版的实现
template<class T>
class CDynArray
{
public:

    CDynArray()
    
{
        mPT 
= NULL;
        nCount 
= 0;
    }


    
~CDynArray()
    
{
        
for(int i=0;i<nCount;i++)
            delete mPT[i];
        free(
this->mPT);
    }


    
int AddItem(T mT)
    
{
        
int i = nCount++;
        
this->mPT = (T**)realloc(mPT,sizeof(T*)*nCount);
        
this->mPT[i] = new T(mT);
        
return i;
    }


    
int GetCount()
    
{
        
return nCount;
    }


    T
& operator [] (int nIndex)
    
{
        
return *mPT[nIndex];
    }


    
void Release()
    
{
        
for(int i=0;i<nCount;i++)
            delete mPT[i];
        free(
this->mPT);
        mPT 
= NULL;
        nCount 
= 0;
    }


protected:
    
int nCount;
    
private:

public:
    T
** mPT;
}
;

如果要往这个结构中添加内容,所添加的结构必须实现拷贝构造函数. 以满足 additem函数的需求,可能我这里设计的不是很好,希望有大侠能指点下.

放个节点对象的实现.
class CLinkMan
{
public:
    
int nIndex;           //索引
    int nParIndex;        //父索引
    int nType;            //类型  1为部门,2为人
    int nDeptIndex;       //所属部门索引

    TCHAR tcValue[
128];      //
    TCHAR tcValueIndex[128]; //值的索引

    CLinkMan()
    
{
        nIndex 
= -1;
        nParIndex 
= -1;
        nType 
= -1;
        nDeptIndex 
= -1;

        tcValue[
0= NULL;
        tcValueIndex[
0= NULL;
    }


    CLinkMan(
const CLinkMan& temp)
    
{
        
this->nIndex = temp.nIndex;
        
this->nParIndex = temp.nParIndex;
        
this->nType = temp.nType;
        
this->nDeptIndex = temp.nDeptIndex;

        wsprintf(
this->tcValue,_T("%s"),temp.tcValue);
        wsprintf(
this->tcValueIndex,_T("%s"),temp.tcValueIndex);
    }


    CLinkMan
& operator = (CLinkMan& temp)
    
{
        
this->nIndex = temp.nIndex;
        
this->nParIndex = temp.nParIndex;
        
this->nType = temp.nType;
        
this->nDeptIndex = temp.nDeptIndex;

        wsprintf(
this->tcValue,_T("%s"),temp.tcValue);
        wsprintf(
this->tcValueIndex,_T("%s"),temp.tcValueIndex);

        
return *this;
    }


    
void Reset()
    
{
        nIndex 
= -1;
        nParIndex 
= -1;
        nType 
= -1;
        nDeptIndex 
= -1;

        tcValue[
0= NULL;
        tcValueIndex[
0= NULL;
    }


protected:
private:

}
;

最后的一些思考,在模版的设计里面,对于内存的申请,我是要多少,申请多少,应该可以考虑每次申请一批,慢慢用.
不过在结构不太大的情况下,应该没什么问题的.