C++实现Vector容器的基本功能

时间:2021-11-12 18:40:53

  本文只实现了Vector的默认构造函数、赋值构造函数、赋值函数、析构函数、重置空间大小函数和插入函数,权当起到抛砖引玉的作用,其他函数功能的实现可在此基础之上进行拓展。

#include <iostream>
using namespace std; template <class T>
class Vector { public:
// 构造函数
Vector(int size=):theSize(size),theCapacity(size+SPACE_CAPACITY){
data = new T[theCapacity];
} // 复制构造函数
Vector(const Vector& other) :theSize(),theCapacity(),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 = ; 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 = ; i < theSize; ++i)
data[i] = temp[i];
delete[] temp;
}
// push_back函数
void push_back(T val) {
if (theSize == theCapacity)
reServe( * theCapacity + );
data[theSize++] = val;
}
private:
const int SPACE_CAPACITY = ;
int theCapacity;
int theSize;
T *data;
};