C++day7(异常处理机制、Lambda表达式、类型转换、STL标准库模板、迭代器、list)

 

#include <iostream>

using namespace std;
template <typename T>
class vector
{
private:
    T* first;
    T* last;
    T* end;
public:
    vector():first(new T),last(first),end(first){cout<<"无参构造"<<endl;}//无参构造
    vector(T* f):first(f),last(f),end(f)//有参构造
    {cout<<"有参构造"<<endl;}
    vector(const vector &other)://拷贝构造
        first(new T[other.end-other.first]),
        last(first+(other.last-other.first)),
        end(first+(other.end-other.first))
    {
        memcpy(this->first,other.first,sizeof(T)*(other.end-other.first));
    }
    vector & operator=(const vector &other)//拷贝赋值都用深拷贝
    {
        if(this!=&other)
        {
            first = new T[other.end-other.first];
            last = first+(other.last-other.first);
            end = first+(other.end-other.first);
            memcpy(this->first,other.first,sizeof(T)*(other.end-other.first));
        }
        return *this;
    }
    T &at(int index)//返回索引的值
    {
        return *(this->first+index);
    }
    bool empty()//判空
    {
        return first==last?true:false;
    }
    T &front()//返回首部元素
    {
        return *this->first;
    }
    T &back()//返回尾部元素
    {
        return *(this->last-1);
    }
    int size()//求元素个数
    {
        return last-first;
    }
    void clear()//清空
    {
        this->last=this->first;
    }
    void expand()//二倍扩容
    {
        T *temp = new T[2*(this->size()*sizeof(T))];

        memcpy(temp,first,sizeof(T)*this->size());
        delete this->first;
        this->first = nullptr;
        this->last = nullptr;
        this->end = nullptr;
        first = temp;
        last = first+sizeof (T)*this->size();
        end = last+sizeof(T)*this->size();
    }
    void push_back(T value)
    {
        *(this->last++) = value;
        if(this->last==this->end)
            this->expand();
    }
    void pop_back()
    {
        this->last--;
    }

};

int main()
{
    vector<int> V;
    V.push_back(1);
    V.push_back(2);
    V.push_back(3);
    V.push_back(4);
    V.push_back(5);
    cout<<V.at(1)<<endl;
    cout<<V.size()<<endl;
    if(V.empty())
    {
        cout<<"空"<<endl;
    }
    else
        cout<<"非空"<<endl;
    cout<<V.back()<<endl;
    cout<<V.front()<<endl;
    V.pop_back();
    V.pop_back();
    for(int i=0;i<V.size();i++)
    {
        cout<<V.at(i)<<" ";
    }
    cout<<endl;
    V.clear();

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值