7.24 作业

1.自己封装vector

template<typename T>
class Myverctor
{
    T* first;
    T* last;
    T* end;
public:
    Myverctor():first(NULL),last(NULL),end(NULL){}
    Myverctor(int num,T data):first(new T[num])
    {
        last = end = first + num;
        for(int i = 0;i<num;i++) first[i] = data;
    }
    Myverctor(const Myverctor &v):first(new T[v.last-v.first]),
        last(v.last),end(v.last)
    {
        for(int i = 0;first+i!=end;i++) first[i] = v.first[i];
    }
    ~Myverctor()
    {
        delete [] first;
    }
    Myverctor & operator = (const Myverctor v)
    {
        delete [] first;
        first = new T[v.last-v.first];
        end = last = v.last;
        for(int i = 0;first+i!=end;i++) first[i] = v.first[i];
        return &this;
    }
    void expand()
    {
        if(end == first)
        {
            first = new T;
            last = first;
            end = first+1;
        }
        else
        {
            int len = end - first;
            T* t = new T[2*len];
            int i = 0;
            for(;first+i!=last;i++) t[i] = first[i];
            delete [] first;
            first = t;
            last = t+i;
            end = t+2*len;
        }
    }
    bool empty()
    {
        return last==first;
    }
    bool full()
    {
        return last==end;
    }
    T& at(int p)
    {
        try {
            if(empty()) throw 1;
            if(p<0||p>=last-first) throw 2;
            else return first[p];
        } catch (int e) {
            if(e==1)
                cout<<"vector为空"<<endl;
            if(e==2)
                cout<<"下标错误"<<endl;
        }
    }
    T& front()
    {
        try {
            if(empty()) throw 1;
            else return *first;
        } catch (int e) {
            cout<<"vector为空"<<endl;
        }
    }
    T& back()
    {
        try {
            if(empty()) throw 1;
            else return *last;
        } catch (int e) {
            cout<<"vector为空"<<endl;
        }
    }
    int size()
    {
        return last-first;
    }
    void clear()
    {
        last = first;
    }
    void push_back(T t)
    {
        if(full()) expand();
        *last++ = t;
    }
    void pop_back()
    {
        if(empty()) return;
        last--;
    }
};

2.思维导图

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值