1. 实现vector相关函数
#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T* first;
T* last;
T* end;
public:
Myvector(int size =10){ //构造函数
this->first = new T[size];
this->last = this->first;
this->end = this->first+size;
}
~Myvector() { //析构函数
delete []first;
this->first=nullptr;
this->last=nullptr;
this->end=nullptr;
}
Myvector(const Myvector& other) //拷贝构造
{
int size = other.end - other.first;
this->first = new T[size];
int len = other.last - other.frist;
memcpy(this->_frist, other._first,sizeof(T)*len);
this->_last = this->_frist + len;
this->_end = this->_frist + size;
}
//容器是否为空?
bool empty()
{
return this->last == this->first;
}
//容器是否为满?
bool full()
{
return this->last == this->end;
}
T &front()
{
return *this->first;
}
T &back()
{
return *(this->last-1);
}
void clear()
{
this->last = this->first;
}
//有效元素个数
int size()
{
return this->last - this->first;
}
void expand() //二倍扩容
{
int size = this->last - this->first;
T* temp = new T[2*size];
memcpy(temp,this->first,sizeof(T)*(end-first));
delete []first;
this->first = temp;
this->last=this->first+size;
this->end=this->first+2*size;
}
void push_back(const T& e) //尾加
{
if(full())
{
this->expand();
}
*last++ = e;
}
void pop_back() //尾删
{
if(empty()) return;
last--;
}
T &at(int index)
{
if(index < 0 || index>=this->size())
{
cout<<"下标越界"<<endl;
// return -1;
}
return this->first[index];
}
};
int main()
{
Myvector<int> v1;
//判断当前数组是否为空
if(v1.empty()) cout<<"v1 is empty"<<endl;
else cout <<"v1 isn't empty"<<endl;
//输出当前容器的大小
cout<<"v1.size = "<<v1.size()<<endl;
//向容器中放入数据
for(int i = 0;i<10;i++)
{
v1.push_back(20+i); // 向末位插入一个值
}
//遍历所有元素
for(int i=0;i<v1.size();i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
v1.pop_back(); //删除末位元素
v1.front()=0;
v1.back()=999;
cout<<"v1.front = "<<v1.front()<<endl;
cout<<"v1.back = "<<v1.back()<<endl;
//遍历所有元素
for(int i=0;i<v1.size();i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
//清空容器
v1.clear();
cout<<"v1.size = "<<v1.size()<<endl;
return 0;
}
运行结果如下:
v1 is empty
v1.size = 0
20 21 22 23 24 25 26 27 28 29
v1.front = 0
v1.back = 999
0 21 22 23 24 25 26 27 999
v1.size = 0
2. 思维导图