c++->标准模板库->day5

写一个队列标准库模板

一、代码

#include <iostream>

using namespace std;

template <typename T>

class my
{
private:
    T* first;
    T* last;
    T* end;
    T temp;

public:
    //构造函数
    my(int size=2)
    {
        first=new T[size];
        last=first;
        end=first+size;
    }
    //析构函数
    ~my()
    {
        delete []first;
        first=last=end=nullptr;
    }
    //拷贝构造函数
    my(const my &Q)
    {
        //实际占用大小
        int len=Q.last-Q.first;
        //空间大小
        int size=Q.end-Q.first;

        //建立新对象的容量
        this->first=new T[size];
        //拷贝
        memcpy(this->first,Q.first,len*sizeof(T));
        //另外两个指针的指向明确
        this->last=this->first+len;
        this->end=this->first+size;
    }
    //判空
    int empty()
    {
        return this->first == this->last;
    }
    //判满
    int full()
    {
        return this->last == this->end;
    }
    //扩容原则:2倍扩容
    void add()
    {
        //获取之前容量
        int size=this->end-this->first;
        //申请二倍空间
        T* temp=new T[2*size];
        //拷贝原来数值
        memcpy(temp,this->first,size*sizeof(T));
        delete []first;
        this->first=temp;
        this->end=this->first+2*size;
        this->last=this->first+size;
    }
    //队列尾插
    void put_my(const T val)
    {
        //判断队列是否满了
        if(this->full())
        {
            this->add();
        }
        *last=val;
        last++;
    }
    //队列头删除
    void post_my()
    {
        if(this->empty())
        {
            cout<<"队列为空"<<endl;
            return;
        }
        for(int i=1;i<this->len();i++)
        {
            first[i-1]=first[i];
        }
        --last;
    }
    //空间大小
    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<int> v1;
    cout<<"循环输入十个数"<<endl;
    for(int i=0;i<10;i++)
    {
        v1.put_my(i);
    }
    for(int i=0;i<v1.len();i++)
    {
        cout<<v1.at(i)<<" ";
    }
    cout<<endl;
    cout<<"队列删除一个元素"<<endl;
    v1.post_my();
    for(int i=0;i<v1.len();i++)
    {
        cout<<v1.at(i)<<" ";
    }
    cout<<endl;
    cout<<"队列插入一个元素"<<endl;
    v1.put_my(10);
    for(int i=0;i<v1.len();i++)
    {
        cout<<v1.at(i)<<" ";
    }
    cout<<endl;
    return 0;
}

二、执行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值