仿照系统的vector,手动实现一个my_vector。
#include <iostream>
using namespace std;
template<typename T> // 模板类: template <class T>
class my_vector
{
private:
T *first;
T *end; // 大小
T *last; //当前
public:
my_vector(int size = 2)// 构造函数
{
first = new T[size]; //第一次申请空间
last = first; // 说明为空(当前指针)
end = first+size; // 尾指针
cout<<"构造函数"<<endl;
}
~my_vector()// 析构函数
{
delete []first; // 数组的空间释放
first = last = end = nullptr;
cout<<"析构函数"<<endl;
}
my_vector(const my_vector& R)// 拷贝构造函数
{
//计算出原空间的尺寸
int len = R.last - R.first; // 当前尺寸
int size = R.end - R.first; // 尾尺寸
this->first = new T[size]; // 申请空间(尾)
memcpy(this->fist, R.first, len*sizeof(T)); // 需要拷贝的尺寸(当前)
// 更新指针指向
this->last = this->first+len; // 当前
this->end = this->first+size; // 尾
cout<<"拷贝构造函数"<<endl;
}
bool empty() // 判空
{
return this->first == this->last;
cout<<"判空"<<endl;
}
bool full() // 判满
{
return this->end == this->last;
cout<<"判满"<<endl;
}
void greater() //扩容
{
int size = this->end - this->first; //当前尺寸
T* temp = new T [2*size]; // 更新空间尺寸
memcpy(temp, this->first, size*sizeof(T));// 更新内容(既然扩容,肯定满的)
delete []first; //释放旧空间
first = temp; // 更新指针指向
last = first+size; // 当前指针指向尾部
end = first+2*size;
cout<<"扩容"<<endl;
}
void push_back(const T val) // 尾插
{
if(this->full())
{
this->greater(); // 二倍扩容
}
*last = val;
last++;
//cout<<"尾插"<<endl;
}
void pop_back() // 尾删
{
if(this->empty())
{
return;
}
--last;
cout<<"尾删"<<endl;
}
T front()const // 第一个元素
{
return *first;
cout<<"第一个元素"<<endl;
}
int size_vector()
{
return end - first;
cout<<"尺寸"<<endl;
}
int len_vector()
{
return last - first;
cout<<"长度"<<endl;
}
T at(int pos)
{
if(pos<0 || pos>this->len_vector())
{
cout<<"at fail.";
}
cout<<" at:";
return first[pos];
}
};
int main()
{
my_vector<int> v1;
for(int i=0; i<20; i++)
{
v1.push_back(i);
// cout<<v1.len_vector()<<endl;
cout<<v1.size_vector()<<endl;
}
for(int i=0; i<20; i++)
{
cout<<v1.at(i)<<"";
}
cout<<endl;
return 0;
}
测试结果: