c++作业

这篇博客介绍了一个名为my_vct的模板类,实现了动态数组的功能,包括构造、拷贝构造、扩容、插入、删除等操作。示例中展示了如何用my_vct存储整数,并进行插入和打印操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>

using namespace std;
template <typename T>
class my_vct
{
private:
    T* first;
    T* end;
    T* last;
public:
    ~my_vct()
    {
        delete []first;
        first = end = last = nullptr;
    }

    my_vct(int size  = 2)
    {
        //创建了两个T类型大小的空间
        first = new T[size];
        //last指向first
        last = first;
        //end指向末尾
        end = first+size;
    }

    //拷贝构造函数
    my_vct(const my_vct &other)
    {
        //len=当前位置-起始位置,即:计算出当前空间已使用大小
        int len = other.last-other.first;
        //size=末尾位置-起始位置,即:计算出当前空间总大小
        int size = other.end - other.first;

        //申请新的空间
        this->first = new T[size];

        //从other.frist开始拷贝len*sizeof(T)个字节到this->first上
        memcpy(this->first, other.first, len*sizeof(T));

        //将该对象的另外两个指针指向对应位置
        //将last指向最后的元素
        this->last = this->first+len;
        //将end指向末尾
        this->end = this->first+size;
    }

    //判空
    bool empty()
    {
        return this->first == this->last;
    }
    //判满
    bool full()
    {
        return this->last == this->end;
    }

    //2倍扩容
    void greater()
    {
        //原大小
        int size = this->end-this->first;
        //新空间,双倍
        T* temp = new T[2*size];
        //将元空间数据存放到新空间中
        memcpy(temp,this->first,size*sizeof(T));

        //释放原空间
        delete []first;
        //更新指针位置
        first = temp;
        last = first+size;
        end = first+(2*size);
    }

    //尾插
    void push_back( const T val)
    {
        if(this->full())
        {
            this->greater();    //如果满了,进行扩容
        }
        *last = val;
        last++;
    }
    //尾删
    void pop_back()
    {
        if(this->empty())
        {
            return;
        }
        --last;
    }

    //获取第一个数据
    T front() const
    {
        return *first;
    }

    //大小,字节
    int size()
    {
        return end-first;
    }

    //长度,字节
    int len()
    {
        return last-first;
    }

    //访问下标
    T &at(int index)
    {
        if(index<0 || index>this->len())
        {
            cout<<"访问越界"<<endl;
        }

        return  first[index];
    }


};
int main()
{
    my_vct<int> v1;
    for(int i=1;i<=20;i++)
    {
        v1.push_back(i);
    }
    for(int i=0;i<20;i++)
    {
        cout<<v1.at(i)<<"  ";
    }
    cout<<endl;

    cout << "Hello World!" << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值