#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class myvector
{
private:
T *first;
T *last;
T *end;
public:
//定义无参构造
myvector()
{
first = new T[2];
last = first;
end = first + 1;
}
//定义有参构造
myvector(int num,const T &val)
{
first = new T[num + 1];
last = first;
end = first + num;
for(int i = 0; i < num; i++)
{
first[i] = val;
last++;
}
}
//定义拷贝构造函数
myvector(const myvector<T> *other)
{
this->first = new T[other->end - other->first + 1];
this->last = other->last;
this->end = other->end;
for(int i = 0; i < other->end - other->first; i++)
{
this->first[i] = other->first[i];
}
}
//定义拷贝赋值函数
myvector &operator=(const myvector<T> *other)
{
if(this != other)
{
delete []first;
this->first = new T[other->end - other->first + 1];
this->last = other->last;
this->end = other->end;
for(int i = 0; i < other->end - other->first; i++)
{
this->first[i] = other->first[i];
}
}
return *this;
}
//析构函数
~myvector()
{
delete []first;
first = nullptr;
last = nullptr;
end = nullptr;
}
//at函数
T &at(int pos)
{
if(pos > end - first)
{
throw -1;
}
return first[pos];
}
//判空函数
bool empty()
{
if(last == first)
{
return true;
}
else
{
return false;
}
}
//判满函数
bool full()
{
if(last == end)
{
return true;
}
else
{
return false;
}
}
//front函数
T &front()
{
return *first;
}
//back函数
T &back()
{
return *(end - 1);
}
//size函数
int size()const
{
return last - first;
}
//clear函数
void clear()
{
last = first;
}
//二倍扩容函数
void expand()
{
T *temp = new T[(end - first) * 2];
for(int i = 0; i < end - first; i++)
{
temp[i] = first[i];
}
delete []first;
first = temp;
end = first + 2 * (end - first);
temp = nullptr;
}
//实现push_back
void push_back(const T &val)
{
if(full())
{
expand();
}
*last = val;
last++;
}
//实现pop_back
void pop_back()
{
if(empty())
{
throw -2;
}
last--;
}
//实现 begin
const T *begin()const
{
return first;
}
//end
const T *endsnd()const
{
return last;
}
};
int main()
{
myvector<int> v1(5,6);
cout << "v1容器中的元素为: " ;
for(int i = 0; i < v1.size(); i++)
{
cout << v1.at(i) << '\t';
}
cout << endl;
v1.clear();
v1.push_back(1465);
v1.push_back(235);
v1.push_back(345);
v1.push_back(88);
v1.push_back(5218);
cout << "v1容器中的元素为: " ;
for(int i = 0; i < v1.size(); i++)
{
cout << v1.at(i) << '\t';
}
cout << endl;
return 0;
}
DAY49
最新推荐文章于 2024-08-19 18:41:12 发布