使用类模板简单实现STL Vector
#include <iostream>
using namespace std;
template<typename T>
class MyVector {
public:
//构造函数
MyVector<T>(int size = 10) {
T * _tep = new T[size]();
first = _tep;
last = _tep;
end = first + size;//
cout << "构建Vector,首地址" << first << endl;
}
//拷贝构造
MyVector<T>(const MyVector<T> & _src) {
//对方vector是为空
if (_src.Empty()) {
int srcVectorySize = _src.getVectorSize();
T * _tep = new T[srcVectorySize]();
first = _tep;
last = _tep;
end = first + srcVectorySize;//
cout << "拷贝构造构建Vector,空拷贝" << endl;
}
else {
int srcVectorySize = _src.getVectorSize();
T * _tep = new T[srcVectorySize]();
first = _tep;
last = _tep;
end = first + srcVectorySize;//
T * _srcVectorElementPoint = _src.first;
while (_srcVectorElementPoint < _src.last) {
*_tep = *_srcVectorElementPoint;
_tep++;
_srcVectorElementPoint++;
}//end
last=_tep;
cout << "拷贝构造构建Vector" << endl;
}
}
//赋值函数
MyVector<T> & operator=(const MyVector<T> & _src)
{
//避免重复
if (this == &_src) { return *this; }
//释放现有堆上资源空间
if (this->Empty() == false) {
delete[]first;
first = nullptr;
last = nullptr;
end = nullptr;
}
int srcVectorySize = _src.getVectorSize();
T * _tep = new T[srcVectorySize]();
first = _tep;
last = _tep;
end = first + srcVectorySize;//
T * _srcVectorElementPoint = _src.first;
while (_srcVectorElementPoint < _src.last) {
*_tep = *_srcVectorElementPoint;
_tep++;
_srcVectorElementPoint++;
}//end
last = _tep;
cout << "赋值函数构建Vector" << endl;
}
//析构函数
~MyVector<T>() {
if (Empty() == false) {
delete[]first;
first = nullptr;
last = nullptr;
end = nullptr;
cout << "析构Vector,堆地址"<<first << endl;
}
}
//添加值,返回指向当前元素的指针,返回为 const * 不允许修改
const T * pushBack(const T & _srcValue) {
//满空间,两倍扩容
if (Full()) {
Expend();
}
*last = _srcValue;
last++;
cout << "Vector添加元素,元素地址" << last << endl;
return last;
}
void popBack(){
this->last--;
}
//获取指定下标的值
T getValue(int index) const {
if (index<0) { return *first; }
if (index > this->getVectorSize()) { return *(last-1); }
int flag = 0;
T *elementPoint = first;
while (flag < index) {
elementPoint++;
flag++;
}
cout << "获取Vector元素值,元素地址" << elementPoint <<"元素值"<< *elementPoint << endl;
return *elementPoint;
}
//编辑指定下标元素的值,返回当前节点的指针 不允许通过返回指针修改
const T * eidtValue(int index,const T & _value) {
if (index > this->getVectorSize() || index<0) { return nullptr; }
int flag = 0;
T *elementPoint = first;
while (flag < index) {
elementPoint++;
flag++;
}
*elementPoint = _value;
cout << "编辑Vector元素值,元素地址" << elementPoint << "元素值" << *elementPoint << endl;
return elementPoint;
}
//判断是否为空
bool Empty() const {
if (first == last) { return true; }
return false;
}
//判断空间是否满
bool Full() const{
if (last == end) { return true; }
return false;
}
int getVectorSize() const {
return this->end - this->first;
}
void printVector() const {
cout <&l