C++ implements the basic functions of the Vector container

  This paper only implements the default constructor, assignment constructor, assignment function, destructor, reset space size function and insertion function of Vector. expand.

#include <iostream>  
using namespace std;

template <class T>
class Vector {

public:
    //    构造函数
    Vector(int size=0):theSize(size),theCapacity(size+SPACE_CAPACITY){
        data = new T[theCapacity];
    }

    //     copy constructor 
    Vector( const Vector& other) :theSize( 0 ), theCapacity( 0 ), data(NULL){
         * this = other;
    }
    //     Overload assignment function 
    Vector& operator =(Vector& other) {
         //     Determine whether to assign to itself 
        if ( this == & other)
             return * this ;
         else {
             delete []data;
            theSize = other.theSize;
            theCapacity = other.theCapacity;
            data = new T[theCapacity];

            for (int i = 0; i < theSize; ++i) {
                data[i] = other.data[i];
            }
            return *this;
        }
    }
    //     Destructor 
    ~Vector( void ) {
         delete [] data;
    }
    // Reallocate     space size function 
    void reServe( int newCapacity) {
         if (newCapacity <= theCapacity)
             return ;

        T *temp = data;
        data = new T[newCapacity];
        for (int i = 0; i < theSize; ++i)
            data[i] = temp[i];
        delete[] temp;
    }
    //    push_back函数
    void push_back(T val) {
        if (theSize == theCapacity)
            reServe(2 * theCapacity + 1);
        data[theSize++] = val;
    }
private:
    const int SPACE_CAPACITY = 16;
    int theCapacity;
    int theSize;
    T *data;
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324970145&siteId=291194637