c++day7

仿照vector手动实现自己的myVector,最主要实现二倍扩容功能

#include 
#include
using namespace std;

template 
class myvector
{
private:
    T *first;   // 指向数组的首地址
    T *last;    // 指向数组中最后一个元素的下一个位置
    T *end;     // 指向数组分配内存的末尾位置
public:
    //无参构造
    myvector(){
        first = new T[1]; // 分配一个长度为1的数组
        last = first;   // 初始时,首尾指针相同
        end = first+1;  // 初始时,末尾指针指向下一个位置
        cout<<"无参构造"< *other){
       this->first = new T[other->end - other->first +1];
       this->last = other->last;
        this->end = other->end;
        for(int i = 0;i < other->end - other->first ;i++){
            this->first[i] = other->first[i];
            last+=1;
        }
        end+=(other->end-other->first);

    }
    //拷贝赋值
    myvector &operator=(const myvector *other)
    {
        if(this!=&other)
        {
            delete [] first;
            this->first = new T[other->end - other->first +1];
            this->last = other->last;
            this->end = other->end;
            for(int i = 0;i < other->end - other->first ;i++){
            this->first[i] = other->first[i];
        }
    }
             return *this;
    }
    ~myvector(){
        delete [] first;
        first = nullptr;
        last = nullptr;
        end = nullptr;
    }
    //at()函数
    T &at(int pop)
    {
        if(pop < 0 || pop >end - first)
        {
            throw -1;
        }
        return first[pop];
    }
    const T &operator[](const int pos)const
    {
        return first[pos];
    }
    //判空函数
    bool empty()
    {
        if(last ==first)
            return true;
         else
            return false;
    }
    //判满函数
    bool full(){
        return last == end;
    }
    //front函数 返回第一个元素的地址
    T &front(){
        return *first;
    }
    //back函数 返回最后一个元素的地址
    T &back(){
        return *(end - 1);
    }
    //size()函数
     int size() const{
        return last - first;
    }
     //clear函数
     void clear(){
         last = first;
     }
     //expand()二倍扩容
     void expand(){
         int n = last -first;
         T *temp = new T[(end - first)*2];
         for(int i = 0; i < last -first;++i ){
             temp[i]=first[i];
         }
         delete [] first;
         first = temp;
         last = first + n;
         end = first + 2 *(end - first);
         delete []temp;
         temp = nullptr;
     }
     //push_back()将val值插入末尾
     void push_back(const T &val)
     {
         if(full())
             expand();
         *last = val;
         last+=1;
     }

    //尾删
     void pop_back(){
         if(empty())
         {
             throw -1;
         }
         last--;
     }

};

int main()
{
    myvector v1(3,5);
    for(int i = 0;i < v1.size();i++){
        cout<v2(v1);
    cout<

你可能感兴趣的:(c++,java,算法)