主要:实现二倍扩容
代码段如下:
#include <iostream>
using namespace std;
template <typename T>
class My_vector //数组
{
private:
T * first;
T * last;
T * end;
public:
My_vector() //无参构造
{
cout<<"My_string::无参构造"<<endl;
}
My_vector(int num, T val) //有参构造函数
{
first=new T[15];
end=first+14;
last=first;
for(int i=0;i<num;i++)
{
*last=val;
last++;
}
cout<<"My_string::有参构造"<<endl;
}
My_vector(const My_vector &other):first(new My_vector[other.size()]),last(other.last-other.first+first),end(first+other.size()-1)//拷贝构造
{
for(int i=0;i<(other.last-other.first);i++)
{
first[i]=other.first[i];
}
cout<<"My_string::拷贝构造函数"<<endl;
}
~My_vector(){cout<<"My_string::析构"<<endl;} //析构函数
My_vector &operator=(const My_vector &other) //拷贝赋值
{
if(this!=&other){
first=new T[other.size()];
last=other.last-other.first+first;
end=other.end-other.first+first;
for(int i=0;i<(other.last-other.first);i++)
{
first[i]=other.first[i];
}
cout<<"My_string::拷贝赋值函数"<<endl;
}
return *this;
}
//at()函数,返回指定位置的元素:
T at(T num)
{
if(num<1||num>size())
{
throw 1;
}
return first[num-1];
}
//empty() 判断Vector是否为空(返回true时为空)
bool empty()
{
return last==first;
}
//full() 判断Vector是否为满(返回true时为满)
bool full()
{
return (last-1)==end;
}
//front() 返回第一个元素
T &front()
{
return first[0];
}
//back() 返回最末一个元素函数返回当前vector最末一个元素的引用
T &back()
{
return *(last-1);
}
//size() 返回Vector元素数量的大小
T size()
{
return end-first+1;
}
//clear() 清空所有元素
void clear()
{
last=first;
}
// expand() 二倍扩容函数
void expand()
{
int len=last-first;
T *temp=new T [size()*2];
end=temp+size()*2-1;
for(int i=0;i<(last-first);i++)
{
temp[i]=first[i];
}
delete []first;
last=temp+len;
first=temp;
}
//push_back() 尾插
void push_back(T num)
{
if(full())
{
expand();
}
*last=num;
last++;
}
//pop_back() 尾删
void pop_back()
{
if(empty())
{
cout<<"this My_vector is empty! "<<endl;
return;
}
last--;
cout<<"尾删成功 "<<endl;
}
void show()
{
if(empty())
{
cout<<"没有元素,遍历失败!"<<endl;
}
else
{
cout<<"所有元素为 "<< endl;
for(auto p=first; p!=last; p++)
{
cout<<*p<<" ";
}
cout<< endl;
}
}
};
int main()
{
cout << "欢迎来到 My_vector " << endl;
My_vector<int> mt1(5,8);
//尾插
for(int i=0;i<20;i++)
{
mt1.push_back(i);
}
//返回最大数量
cout<<mt1.size()<<endl;
//遍历
mt1.show();
//返回任意位置值
try {
cout<<mt1.at(0);
} catch (int n) {
if(n==1)
{
cout<<"请输入正确的位置"<<endl;
}
}
//判空,判满
if(mt1.empty())
{
cout<<"空"<<endl;
}
else
cout<<"非空"<<endl;
if(mt1.full())
{
cout<<"满"<<endl;
}
else
cout<<"非满"<<endl;
//返回第一个元素
cout<<"第一个元素为 "<< mt1.front()<<endl;
//back() 返回最末一个元素函数返回当前vector最末一个元素的引用
cout <<"最后一个元素为 "<<mt1.back()<<endl;
//尾删
mt1.pop_back();
mt1.show();
//清空
mt1.clear();
mt1.show();
return 0;
}
实现结果