C++DAY7

封装vector

C++DAY7_第1张图片

 

#include 

using namespace std;

int error = -1;

template 
class Myvector
{
private:
        T *first;
        T *last;
        T *end;
public:
    //构造函数
    Myvector():first(new T),last(first),end(first){}
    //析构函数
    ~Myvector();
    //拷贝构造
    Myvector(const Myvector &other);
    //拷贝赋值
    Myvector &operator = (const Myvector &other);
    //T &at(int index)
    T &at(int index);
    //empty()
    bool empty();
    //full()
    bool full();
    //front()
    T &front();
    //back()
    T &back();
    //size()
    int size();
    //clear()
    void clear();
    //expand()     二倍扩容函数
    void expand();
    //push_back()
    void push_back(const T &val);
    //pop_back()
    void pop_back();
};

template
Myvector::~Myvector()
{
    delete []first;
    delete []last;
    delete []end;

}

template
Myvector::Myvector(const Myvector &other)
{
    this->first = new T[other.end - other.first];
    this->first = other.first;
    this->last = other.last;
    this->end = other.end;


}

template
Myvector &Myvector::operator =(const Myvector &other)
{
    if(this != &other)
    {
        delete [] first;
        this->first = new T[other.end - other.first];
        this->first = other.first;
        this->last = other.last;
        this->end = other.end;
    }
    return *this;
}

template
T &Myvector::at(int index)
{
    return first[index];
}

template
bool Myvector::empty()
{
    return first == last;
}

template
bool Myvector::full()
{
   return last == end;
}

template
T &Myvector::front()
{
    if(empty())
    {
        cout << "空" << endl;
        return error;
    }
   return *first;
}

template
T &Myvector::back()
{
    if(empty())
    {
        cout << "空" << endl;
        return error;
    }
    return *(last -1);
}

template
int Myvector::size()
{
    return last-first;
}

template
void Myvector::clear()
{
    last = first;
}

template
void Myvector::expand()
{
    T *temp = new T[2*size()];
    memcpy(temp,first,sizeof(T)*size());
    delete []first;
    first = temp;
    last = first + size();
    end = first + 2*size();
}

template
void Myvector::push_back(const T &val)
{
    *last++ = val;
    if(last == end)
        expand();
}

template
void Myvector::pop_back()
{
    if(empty())
    {
        cout << "空" << endl;
        return;
    }
    *last = 0;
    last--;
}


int main()
{
    Myvector  v1;
    for(auto i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }

    cout << "size = " << v1.size() << endl;

    for(auto i = 0; i < v1.size(); i++)
    {
        cout << v1.at(i) << " ";
    }
    cout << endl;

    cout << v1.back() << endl;
    cout << v1.front() << endl;

    v1.pop_back();

    for(auto i = 0; i < v1.size(); i++)
    {
        cout << v1.at(i) << " ";
    }
    cout << endl;

    cout << "size = " << v1.size() << endl;

    v1.clear();
    cout << "size = " << v1.size() << endl;
    return 0;
}


C++DAY7_第2张图片

 

你可能感兴趣的:(c++,算法,数据结构)