C++实现Vector容器的基本功能
本文只实现了Vector的默认构造函数、赋值构造函数、赋值函数、析构函数、重置空间大小函数和插入函数,权当起到抛砖引玉的作用,其他函数功能的实现可在此基础之上进行拓展。
#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]; } // 复制构造函数 Vector(const Vector& other) :theSize(0),theCapacity(0),data(NULL){ *this=other; } // 重载赋值函数 Vector& operator=(Vector& other) { // 判断是否为自身赋值 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; } } // 析构函数 ~Vector(void) { delete[] data; } // 重新分配空间大小函数 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; };