码迷,mamicode.com
首页 > 编程语言 > 详细

c++vector简单实现

时间:2015-07-24 16:14:28      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

const  int DEFAULT_CAP = 3;

template <typename T>
class vector {
    //
    int capacity;
    T* _data;
    int _size;
    
public:
    //const
    vector ():capacity(DEFAULT_CAP),_size(0),_data(new T[capacity]){};
    
    vector(vector& v):capacity(v.cap()),_size(v.size()),_data(new T[capacity]) {
        memcpy(_data, v._data, _size*sizeof(T));
    }
    vector(vector&& v):capacity(v.cap()),_size(v.size()) {
        _size = v.getdata();
        v._data = nullptr;
    }
    //deconst
    virtual ~vector(){ delete [] _data;}
    //operator
    vector& operator=(const vector &v) {
        /*
        if(this != &v){
            delete [] _data;
            _size = v.size();
            capacity = v.cap();
            _data = new T[capacity];
            memcpy(_data, v._data, _size*sizeof(T));
        }*/
        sw(v);
        return *this;
    }
    T& operator[](int i) const{
        return _data[i];
    }
    //retrun
    int size() const {return _size;}
    int cap() const {return capacity;}
    const int getdata() const noexcept {_data;}
    //function
    void expand() {
        if(_size == capacity){
            capacity = capacity<<1;
        T *old = _data;
        _data = new T[capacity];
        memcpy(_data, old, _size*sizeof(T));
        delete [] old;
        }
    }
    void push_back(T const& temp) {
        expand();
        _data[_size++] = temp;
    }
    void each(){
        for (int i = 0; i < _size; ++i) {
            cout<<_data[i]<<endl;
        }
    }
    void sw(vector& v) {
        swap(_size, v._size);
        swap(capacity, v.capcity);
        swap(_data, v._data);
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

c++vector简单实现

标签:

原文地址:http://blog.csdn.net/susser43/article/details/47041653

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!