#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T * first;//第一个元素
T * last;//最后一个元素
T * end;//容器最大值
public:
//初始化
Myvector(int size) {
first = new T[size];
last = first;
end = first + size;
}
//构造函数
Myvector(){
first = nullptr;
last = nullptr;
end = nullptr;
}
//析构函数
~Myvector()
{
delete [] first;
}
//拷贝构造函数
Myvector(const Myvector & other)
{
first = new T[other.size()];
last = first + other.size();
end = first + other.capacity();
memcpy(this->first, other.first, other.size()*sizeof(T));
}
//拷贝赋值
Myvector& operator=(const Myvector& other)
{
if(this == &other)
{
return *this;
}
delete []first;
first = new T[other.size()];
last = first + other.size();
end = first + other.capacity();
memcpy(this->first,other.first,other.size()*sizeof (T));
return *this;
}
//at()功能
T& at(int pos)
{
if(pos<0 || pos>=size())
{
cout<<"越界访问"<<endl;
}
else
{
return *(first+pos);
}
}
//empty()功能
bool empty() const
{
return last == first;
}
//full()
bool full() const
{
return end ==last;
}
//front() 访问第一个元素
T& front()
{
if(empty())
{
cout<<"vector为空"<<endl;
}
else
{
return *first;
}
}
//back();访问最后一个元素
T& back()
{
if(empty())
{
cout<<"vector为空"<<endl;
}
else
{
return *(last-1);
}
}
//size()//容量内元素个数
int size() const
{
return last- first;
}
//容量的大小
int capacity() const
{
return end - first;
}
//清空
void clear()
{
for(int i=0;i<size();i++)
{
pop_back();
}
}
//二倍扩容
void expand()
{
int new_capacity = capacity() * 2;
T* new_first = new T[new_capacity];
memcpy(new_first, first, size() * sizeof(T));
delete[] first;
first = new_first;//更新first
last = first + size();//更新last
end = first + new_capacity;
}
//push_back()
void push_back(const T& value)
{
if(full())
{
expand();
}
*last = value;
last++;
}
//pop_back()
void pop_back()
{
if(empty())
{
cout<<"容器为空"<<endl;
}
else
{
last--;
}
}
};
int main()
{
//实例化对象
Myvector<int> v(10);
//添加元素
v.push_back(1);
v.push_back(4);
v.push_back(5);
v.push_back(8);
v.push_back(10);
v.push_back(12);
v.push_back(13);
v.push_back(14);
//删除元素
v.pop_back();
v.pop_back();
//遍历
for(int i=0;i<v.size();i++)
{
std::cout<<"v.at(i)="<<v.at(i)<<endl;
}
//大小
v.size();
std::cout<<"v.size()="<<v.size()<<endl;
//第一个元素
std::cout<<"v.front()="<<v.front()<<endl;
//最后一个元素
std::cout<<"v.back()="<<v.size()<<endl;
//清空
v.clear();
//大小
std::cout<<"v.size()="<<v.size()<<endl;
return 0;
}
现象