数据结构与算法-C++实现动态变长数组

一个简单至极的变长数组,仅仅是在原生数组中添加了自动变长功能

参考STL中vector的实现,每次下标越界,就将数组容量扩大一倍。

  1. 申请新的空间,是原长度的二倍
  2. 从原内存复制所有内容到新内存
  3. 释放原内存
/*
    Author:  trialley
    Date:    2019-7-26
    Licence: MIT
*/

#pragma once
#include<cstring>       //memset,memcpy
#include<cstdlib>       //malloc

template<typename T>
class darray{
    private:
        T* head;        //the array head pointer
        int length;     //the length of array
    public:
        darray(int n=100){
            length=n;
            head=(T*)malloc(sizeof(T)*length);
            memset(head,0,length);
        }
        
        // "&" is a must !
        T& operator [](int i){
            if(i>length){
                exlength();
                return head[i];
            }
            return head[i];
        }
        exlength(){
            int nlength=2*length;
            T* temp=head;
            head=(T*)malloc(sizeof(T)*nlength);
            memset(head,0,nlength);
            memcpy(head,temp,length);
            length=nlength;
        }
};

猜你喜欢

转载自www.cnblogs.com/trialley/p/11248890.html
今日推荐