仿Vector模板类

#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
class vector
{
  public:
    T* first;
    T* last;
    T* end;
    //无参构造
    vector():first(NULL),last(NULL),end(NULL)
    {
    }
    //有参构造
    vector(int n,const T &val)
    {
        first = new T[n];
        last =  first + n;
        end = first + n;
        for(int i=0;i<n;i++)
        {
            *(first+i)=val;
        }
    }
    vector( const T* s, const T* end2)
    {
        first = new T[end2-s];
        end = first+(end2-s);
        last = first;
        for(int i=0;i<(end2 - s);i++)
        {
            *last=*(s+i);
            last++;
        }
    }
    int size()//输出大小
    {
        if(NULL == first)
            return 0;
        else
            return last - first;
    }
    int capacity() //输出容器最大容量
    {
        if(NULL == first)
            return 0;
        else
            return end - first;
    }
    void push_back(const T &val)//尾插
    {
        if(first == NULL)//判断是否是空
        {
            first = new T ;
            last = first;
            end = first + 1;
        }
        if(last == end)
        {
            int s_ize = end-first;
            T* temp = new T[2*s_ize];
            memset(temp,0,2*sizeof(T)*s_ize);
            memcpy(temp,first,sizeof(T)*s_ize);
            delete []first;
            first = temp;
            last = first + s_ize;
            end = first + 2*(s_ize);
        }
        *last = val;
        last = last + 1;
    }
    void pop_back()//尾删
    {
        last--;
    }
    T & at(int num)//定位
    {
        return *(first+num);
    }
};
int main()
{
    vector<int> v1;        //定义一个容器


    cout<<"v1.size = "<<v1.size()<<endl;      //输出容器的大小
    cout<<"v1.capacity = "<<v1.capacity()<<endl;  //输出容器的最大容量


    cout<<"-------------------------------------------------------\n";


    for(int i=1; i<=20; i++) //输入二十个数
    {
        v1.push_back(i);
        cout<<"v1.size = "<<v1.size()<<"    v1.capacity = "<<v1.capacity()<<endl;
        //左边是当前容器的大小  右边是容器的最大容量
    }


    //输出当前vector中的内容
    for(auto i=0; i<v1.size(); i++)
    {
        //cout<<v1[i]<<" ";
        cout<<v1.at(i)<<" ";
    }
    cout<<endl;
    return 0;
}

现象:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值