重写vector
#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
class Myvector
{
private:
T * first; //头
T * last; //尾
T * end; //标志
public:
// 构造函数
Myvector(); //无参
Myvector(int s); //有参
// 析构函数
~Myvector();
// 拷贝构造
Myvector( const Myvector &other);
// 拷贝赋值
Myvector &operator=(const Myvector &other);
// 下标访问
T at(int x);
// 判空
bool empty();
// 判满
bool full();
// 查看头
T front();
// 查看尾
T back();
// 计算容器数据的个数
int size(Myvector &other);
// 删除容器中的所有元素
void clear(Myvector &other);
// 二倍扩容函数
void expand();
// 尾插
void push_back(const T &s);
// 尾删
void pop_back();
// 遍历
void show();
};
// 构造函数
// 无参构造
template <typename T>
Myvector<T>::Myvector():first(new T(1))
{
this->last = this->first;
this->end = first+1;
}
// 有参构造
//template <typename T>
//Myvector<T>::Myvector(int s)
//{
// this->first = new T(s);
// this->last = this->first;
// this->end = s;
//}
// 析构函数
template <typename T>
Myvector<T>::~Myvector()
{
delete []this->first;
}
// 拷贝构造
template <typename T>
Myvector<T>::Myvector( const Myvector &other ):first(other.first),last(other.last),end(other.end)
{}
// 拷贝赋值
//template <typename T>
//Myvector<T>::Myvector&operator=(const Myvector &other)
//{}
// 下标访问
template <typename T>
T Myvector<T>::at(int s)
{
if(s < 0 && s >= this->last)
{
cout<<"下标不合法"<<endl;
return ;
}
return this->first[s];
}
// 判空
template <typename T>
bool Myvector<T>::empty()
{
return this->first == this->last?true:false;
}
// 判满
template <typename T>
bool Myvector<T>::full()
{
return this->last == this->end?true:false;
}
// 查看头
template <typename T>
T Myvector<T>::front()
{
if(this->first == this->last)
{
cout<<"栈空"<<endl;
return;
}
return *(this->first);
}
// 查看尾
template <typename T>
T Myvector<T>::back()
{
if(this->first == this->last)
{
cout<<"栈空"<<endl;
return;
}
return *(this->last-1);
}
// 计算容器数据的个数
template <typename T>
int Myvector<T>::size(Myvector &other)
{
return other.last-1;
}
// 删除容器中的所有元素
template <typename T>
void Myvector<T>::clear(Myvector &other)
{
other.last = other.first;
}
// 二倍扩容函数
template <typename T>
void Myvector<T>::expand()
{
int size = this->end - this->first;
size_t n = sizeof(T) * size;
// 申请二倍空间
T* temp = new T[size * 2];
// 拷贝内容
memcpy (temp, this->first, n);
// 释放原有空间
delete []this->first;
// 重新设置指针指向
this->first = temp;
this->last = this->first + n / sizeof(T);
this->end = this->first + size * 2;
}
// 尾插
template <typename T>
void Myvector<T>::push_back(const T &s)
{
if(full())
{
expand();
}
*(this->last) = s;
this->last = this->last+1;
}
// 尾删
template <typename T>
void Myvector<T>::pop_back()
{
if(empty())
{
cout<<"容器为空"<<endl;
return;
}
this->last = this->last-1;
}
// 遍历
template <typename T>
void Myvector<T>::show()
{
for(int i = 0; i < end - first; i++)
{
cout<<first[i]<<" ";
}
cout<<endl;
}
int main()
{
Myvector<int> s1;
s1.push_back(1);
s1.push_back(4);
s1.push_back(7);
s1.push_back(8);
s1.show();
return 0;
}