1.封装标准模板库(STL)---Vectors容器模板(已优化);
#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T *first; //指向堆区空间容器的首地址
T *last; //指向容器最后一个元素的下一个位置
T *end; //指向容器的最大位置
public:
//构造函数
Myvector(int size = 3)
{
first = new T[size];
last =first; //说明容器空
end = first + size;
}
//析构函数
~Myvector()
{
delete [] first;
first = nullptr;
last = nullptr;
end = nullptr;
}
//拷贝构造
Myvector(const Myvector<T> &other)
{
int size = other.size(); //当前长度
int max_size = other.max_size(); // 当前最大容量
first = new T[max_size];
memcpy(first,other.first,sizeof (T)*size);
last = first + size;
end = first + max_size;
}
//拷贝赋值
Myvector &operator =(const Myvector<T> &other)
{
if(this != &other)
{
delete [] first;
int size = other.size();
int max_size = other.max_size();
first = new T[max_size]; //新空间大小
memcpy(first,other.first,sizeof (T)*size);
last = first + size;
end = first + max_size;
}
return *this;
}
//empty() 判空
bool empty()
{
return last==first;
}
//full() 判满
bool full()
{
return last==end;
}
//clear() 清空元素
void clear()
{
last=first;
}
//size() 当前vector中元素的长度
int size() const
{
return last-first;
}
//max_size() 当前vector的最大容量
int max_size() const
{
return end-first;
}
//push_back() 尾插元素
void push_back(const T elem)
{
if(full() == true)
{
cout<<"容器已满,2倍扩容后继续插入>>> "<<endl;
expand();
}
*last = elem;
last++;
}
//pop_back() 尾删元素
void pop_back()
{
if(empty() == true)
return;
last--;
}
//T &at(int index) 查询元素
T &at(int index)
{
if(index<0 || index>=size())
throw string("访问越界!"); //异常处理
return first[index];
}
//front() 返回首元素的引用
T &front()
{
if(!empty())
return *first;
throw string("myvector空");
}
//back() 返回尾元素的引用
T &back()
{
if(!empty())
return *(last-1);
throw string("myvector空");
}
//expand() 二倍扩容
void expand()
{
int Msize = end - first;
T *temp = new T[2*Msize]; //堆区申请一个2倍容器最大容量的空间
memcpy(temp,first,sizeof(T)*Msize); //更新数据
delete [] first; //释放原空间
first = temp; //更新first指向
last = first + Msize; //更新其他指针
end = first + 2*Msize;
}
//遍历
void Output()
{
for(int i=0; i<size(); i++)
{
cout<<first[i]<<" ";
}
cout<<endl;
}
};
int main()
{
Myvector<int> v1;
if(v1.empty()) //判空
cout<<"v1空"<<endl;
else
cout<<"v1不空"<<endl;
for(int i=0; i<6; i++) //尾插
{
int elem;
cout<<"输入要插入的元素>>> ";
cin>>elem;
v1.push_back(elem);
}
v1.Output(); //遍历
cout<<"v1.size= "<<v1.size()<<endl;
v1.pop_back(); //尾删
cout<<"尾删一个元素后>>> ";
v1.Output(); //遍历
cout<<"第一个元素>>> "<<v1.front()<<endl; //首尾元素
cout<<"最后一个元素>>> "<<v1.back()<<endl;
cout<<"v1.at(0)>>> "<<v1.at(0)<<endl; //查找元素
cout<<"v1.at(1)>>> "<<v1.at(1)<<endl;
cout<<endl;
Myvector<int> v2(v1); //拷贝构造
cout<<"拷贝构造v2>>> ";
v2.Output();
Myvector<int> v3; //拷贝赋值
v3 = v1;
cout<<"拷贝赋值v3>>> ";
v3.Output();
v1.clear(); //清空
v2.clear();
v3.clear();
cout<<"v1v2v3清空后>>> ";
v1.Output(); //遍历
v2.Output();
v3.Output();
return 0;
}